gogo-gorm

GORM load associations from existing object


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?
  }
}

Solution

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

    For more details, see the GORM documentation on Association Mode