I have the following two models: File
and Session
, and a single session could have many File objects (one-to-many).
type Session struct {
gorm.Model
Name string `json:"name,omitempty"`
IsCurrent bool `json:"is_current"`
Files []File `gorm:"foreignkey:SessionID" json:"files"`
}
type File struct {
gorm.Model
Name string `json:"name"`
FileType string `json:"file_type"`
ParentName string `json:"parent_name"`
SessionID uint `json:"session_id"`
}
I'd like to get all the files associated to the session that has IsCurrent = true
I wrote the following raw SQL query that seems to work fine, but I'd like to know if there's any way to do a similar query int he Gorm way.
err = db.Raw("SELECT * FROM files, sessions WHERE files.session_id == sessions.id AND sessions.is_current = ?", true).Scan(&fileObjects).Error
@TonyGW the key is using a combination of Preload
and Where
in your Gorm call.
currentSession := &Session{}
err := db.Model(&Session{}).Preload("Files").Where(&Session{IsCurrent: true}).Find(¤tSession).Error
if err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("%+v
", currentSession)
FYI
There are a number of ways you can structure the Where
query. Eg,
db.Model(&Session{}).Preload("Files").Where("is_current = ?", true).Find(¤tSession)
and also using a map to build up multiple Where
conditions,
db.Model(&Session{}).Preload("Files").Where(map[string]interface{}{
"is_current": true,
"something_else": "value",
}).Find(¤tSession)
I hope that helps!
Try this one
db.Where("is_current = ?", true).Model(&session).Related(&session.Files)