通过外键联合查询

Joint queries through foreign key

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

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

试试这个

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

@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)

仅供参考

您可以通过多种方式构建 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)

希望对您有所帮助!