Gorm: Support associations for Scan

Created on 31 May 2015  路  8Comments  路  Source: go-gorm/gorm

Hey,

is it possible to scan associations, because I tried but it didn't work so far:

var events []Event

self.DAO.DB.Raw("SELECT"+
    " e.ID, e.title, e.description,"+
    " d.ID, d.date, d.start_time, d.end_time,"+
    " d.event_id"+
    " FROM events e"+
    " LEFT JOIN dates d ON e.ID = d.event_id").
    Scan(&events)

For the following two example structs:

type Event struct {
    ID int
    Title string
    Description string
    Dates []Date
}

type Date struct {
    ID int
    Date time.Time
    StartTime time.Time
    EndTime time.Time
    EventID int
}

It is not populating the Dates property, so it stays nil.

question

Most helpful comment

Same issue; this appears to be valid, Preload isn't doing anything with Rows as far as I can see, this bug should likely be re-opened

All 8 comments

I have the same issue. I've searched and it seems that gorm does not support scanning associations on joins. Can anyone confirm? The way I've bypassed this issue is by scanning the values myself row by row.

Hi @codingrogue

Yes, doesn't support Scan association, maybe you want to use Preload here?

How to use Preload? I have tried

rows, err := pDb.
        Model(&entity.User{}).
        Preload(`UserProfiles`).
        Order(`id ASC`).
        Rows()

but it is not working. db.ScanRow only populate user object except UserProfiles field

Can confirm, Preload does nothing when using Rows or in ScanRows

Please re-open this

Has anyone found a solution for this?
Im experiencing something similar.

Came here for a same reason - Preload does not loading associations. Please, let us know if there any additional info.

Currently I'm using this temporary solution:
sql := "SELECT table.id ...

then I getting result as array (http://gorm.io/docs/sql_builder.html) and then just

db.Where("id in (?)", ids).Preload("Column").Find(&models);

It takes one more SQL query but still better than loading associations for each entity

Same issue; this appears to be valid, Preload isn't doing anything with Rows as far as I can see, this bug should likely be re-opened

Same issue. I hope to support this feature. @jinzhu

Was this page helpful?
0 / 5 - 0 ratings