【问题标题】:gorm: fetch relation later (without preloading)gorm:稍后获取关系(不预加载)
【发布时间】:2021-09-14 20:11:35
【问题描述】:

我知道我可以预加载模型中定义的关系,但是如果我有一个未预加载的对象,我还没有找到以后如何加载关系的任何方法。

示例:

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

现在我可以:

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

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

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

感谢您的提示。

【问题讨论】:

    标签: go lazy-loading go-gorm


    【解决方案1】:

    遵循文档中的find associations 指南:

    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)
    

    【讨论】:

    • 就像这样它抛出“无效值,应该是指向结构或切片的指针”的作品,如果我先初始化结构://现在如何获取用户? template.User = User{} db.Model(&template).Association("User").Find(template.User)
    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 2021-03-25
    • 2017-04-23
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多