通过外键联合查询

时间:2018-04-14 06:45:17

标签: sql go go-gorm

我有以下两个模型:FileSession,单个会话可以有多个File对象(一对多)。

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"`
}

我希望获得与IsCurrent = true

会话相关联的所有文件

我编写了以下原始SQL查询似乎工作正常,但我想知道是否有任何方式以Gorm方式进行类似的查询。

  

err = db.Raw(" SELECT * FROM files,sessions WHERE files.session_id == sessions.id AND sessions.is_current =?",true).Scan(& fileObjects).Error

2 个答案:

答案 0 :(得分:0)

试试这个

db.Where("is_current = ?", true).Model(&session).Related(&session.Files)

答案 1 :(得分:0)

@TonyGW关键是在Gorm调用中使用PreloadWhere的组合。

currentSession := &Session{}

err := db.Model(&Session{}).Preload("Files").Where(&Session{IsCurrent: true}).Find(&currentSession).Error
if err != nil {
  fmt.Println("Error:", err)
}

fmt.Printf("%+v\n", currentSession)

<强> FYI

您可以通过多种方式构建Where查询。例如,

db.Model(&Session{}).Preload("Files").Where("is_current = ?", true).Find(&currentSession)

并使用地图构建多个Where条件,

db.Model(&Session{}).Preload("Files").Where(map[string]interface{}{
  "is_current": true,
  "something_else": "value",
}).Find(&currentSession)

我希望有所帮助!