【问题标题】:Joint queries through foreign key通过外键联合查询
【发布时间】:2018-04-14 06:45:17
【问题描述】:

我有以下两个模型: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

【问题讨论】:

    标签: sql go go-gorm


    【解决方案1】:

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

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      试试这个

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-18
        • 2019-12-04
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 2014-01-08
        • 2012-03-31
        • 2011-08-14
        相关资源
        最近更新 更多