Search code examples
golazy-loadinggo-gorm

gorm: fetch relation later (without preloading)


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.


Solution

  • 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)