I know I can preload associations like this:
type User struct {
Name string
Documents []Document
}
type Document struct {
Name string
}
func loadUser() {
var u User
db.Preload("Documents").First(&u) // loads correctly and populates u.Documents
}
But what if I have the user object already loaded and I just want to load the associated objects on it?
func loadUser() {
var u User
db.First(&u) // load the plain user object
if gonnaNeedTheDocs {
// how can I populate u.Documents (or any other associations) here efficiently?
}
}
If you’ve already loaded the User
object and only want to load the Documents
association when needed, you can use GORM’s Association()
method. This avoids reloading the entire user record:
if gonnaNeedTheDocs {
db.Model(&u).Association("Documents").Find(&u.Documents)
}
This will:
Use the already-loaded u
as the base model,
Access the "Documents"
association,
And populate u.Documents
with the related records.
For more details, see the GORM documentation on Association Mode