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

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

gorm: fetch relation later (without preloading)

问题

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

示例:

type Template struct {
    ID     uint   `gorm:"primary_key"`
    Name   string
    UserID *uint
    User   *User  `gorm:"foreignkey:UserID"`
}

现在我可以这样做:

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

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

db.First(&template)
assert.Nil(template.User)
//如何现在获取User?
...
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:

type Template struct {
    ID uint `gorm:"primary_key"`
    Name     string
    UserID *uint
    User   *User `gorm:"foreignkey:UserID"`
}

Now I can:

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

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

db.First(&template)
assert.Nil(template.User)
//how to fetch the user now?
...
assert.NotNil(template.User)

thanks for tips.

答案1

得分: 2

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

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

Follow the find associations guide in the docs:

db.First(&template)
assert.Nil(template.User)
//how to fetch the user now?
db.Model(&template).Association("User").Find(template.User)
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:

确定