gorm: 后期获取关联(无需预加载)

huangapple go评论104阅读模式
英文:

gorm: fetch relation later (without preloading)

问题

我知道我可以预加载模型中定义的关系,但是我还没有找到任何方法来在没有预加载的情况下加载关系。

示例:

  1. type Template struct {
  2. ID uint `gorm:"primary_key"`
  3. Name string
  4. UserID *uint
  5. User *User `gorm:"foreignkey:UserID"`
  6. }

现在我可以这样做:

  1. db.Preload("User").Find(&templates)

但是如果我只想稍后获取User呢?

  1. db.First(&template)
  2. assert.Nil(template.User)
  3. //如何现在获取User?
  4. ...
  5. assert.NotNil(template.User)

谢谢提供的提示。

英文:

I know I can preload a relation defined in the model, but have not found any way how to load the relation later if I have an object which was not preloaded.

Sample:

  1. type Template struct {
  2. ID uint `gorm:"primary_key"`
  3. Name string
  4. UserID *uint
  5. User *User `gorm:"foreignkey:UserID"`
  6. }

Now I can:

  1. db.Preload("User").Find(&templates)

But what if I just want to fetch the User later?

  1. db.First(&template)
  2. assert.Nil(template.User)
  3. //how to fetch the user now?
  4. ...
  5. assert.NotNil(template.User)

thanks for tips.

答案1

得分: 2

按照文档中的查找关联指南进行操作:

  1. db.First(&template)
  2. assert.Nil(template.User)
  3. //如何现在获取用户?
  4. db.Model(&template).Association("User").Find(template.User)
  5. assert.NotNil(template.User)
英文:

Follow the find associations guide in the docs:

  1. db.First(&template)
  2. assert.Nil(template.User)
  3. //how to fetch the user now?
  4. db.Model(&template).Association("User").Find(template.User)
  5. assert.NotNil(template.User)

huangapple
  • 本文由 发表于 2021年9月15日 04:11:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69184014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定