2018-04-14 06:45
浏览 150


I have the following two models: File and Session, and a single session could have many File objects (one-to-many).

type Session struct {
    Name            string       `json:"name,omitempty"`    
    IsCurrent       bool         `json:"is_current"`
    Files     []File `gorm:"foreignkey:SessionID" json:"files"`

type File struct {
    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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtpoius74857 2018-04-18 02:06

    @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(&currentSession).Error
    if err != nil {
      fmt.Println("Error:", err)
    ", currentSession)


    There are a number of ways you can structure the Where query. Eg,

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

    and also using a map to build up multiple Where conditions,

      "is_current": true,
      "something_else": "value",

    I hope that helps!

    点赞 打赏 评论
  • dongxu6418 2018-04-14 12:45

    Try this one

    db.Where("is_current = ?", true).Model(&session).Related(&session.Files)
    点赞 打赏 评论

相关推荐 更多相似问题