douyiyi5284 2019-07-01 08:43
浏览 25
已采纳

多人一对一返回空

I want to use gorm the use a many to one relationship in my project. My structs are like this:

type Book struct {
    ID          uint
    Title       string
    Subtitle    string
    Chapters    []Chapter `gorm:"foreignkey:BookID;association_foreignkey:ID"`

} }

// TableName is book
func (Book) TableName() string {
    return "book"
}

// Chapter of books
type Chapter struct {
    ID      uint
    BookID  string
    Chapter string
}

What I want is to get chapters of a book by using this command:book.chapters. I use the following codes to get books and chapters:

var book models.Book
    db.First(&book, "id = ?", 4)
    fmt.Println(book.ID, book.Chapters) // returns []

when I query chapters with book_id = 4, I get 11 results:

   var chapters []models.Chapter
   db.Find(&chapters, "book_id = ? ", 4)
   fmt.Println("len(chapters) = ", len(chapters)) // len(chapters) =11

and when I set db.LogMode(true) and see what happens in the code I see that querying book only queries the books not joining that with chapters:

SELECT * FROM "book" WHERE (id = 4) ORDER BY "book"."id" ASC LIMIT 1

Is there something that I missed from the documentation? how should I make the book struct the get non-empty book.chapters.

  • 写回答

1条回答 默认 最新

  • duanlie7962 2019-07-01 09:20
    关注

    Your problem is probably in Preloading: http://gorm.io/docs/preload.html#Preload

    Try the following:

    var book models.Book
    db.Preload("Chapters").First(&book, "id = ?", 4)
    fmt.Println(book.ID, book.Chapters)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line