1
votes

Structs:

type (
  User struct{
    ID int64
    Name string
  }
  Group struct{
    ID int64
    Name string
    Users []User
  }
)

I Insert width:

users := []User{}
user := User{ID: int64(1)}
gormConn.First(&user) // .Error is nil, user with ID=1 exists
users = append(users, user)

group := Group{
  Name: "Grrr",
  Users: users,
}
gormConn.Create(&group)

But when I call gormConn.Find(&groups), I will get [{id: 1, name: "Grrr", users: null}] instead of [{id: 1, name: "Grrr", users: [{id:1, name: "Usr"}]}]

Also in SQL table groups column users not found. (all structs will gormConn.AutoMigrate)

1

1 Answers

1
votes

Loading the foreign key related tables using ORM is called as Eager Loading. EagerLoading is off by default in GORM by using Find(). Better use Preload() for loading the nested data.

Link for official documentation - http://jinzhu.me/gorm/crud.html#preloading-eager-loading