【问题标题】:Golang GORM and several tables associationsGolang GORM 和几个表的关联
【发布时间】:2016-05-17 19:16:43
【问题描述】:

结构:

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

I 插入宽度:

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)

但是当我调用gormConn.Find(&groups) 时,我会得到[{id: 1, name: "Grrr", users: null}] 而不是[{id: 1, name: "Grrr", users: [{id:1, name: "Usr"}]}]

同样在 SQL 表 groupsusers 中未找到。 (所有结构都将gormConn.AutoMigrate

【问题讨论】:

    标签: go orm go-gorm


    【解决方案1】:

    使用 ORM 加载外键相关表称为 Eager Loading。 EagerLoading 在 GORM 中默认是关闭的,使用 Find()。最好使用Preload() 加载嵌套数据。

    官方文档链接 - http://jinzhu.me/gorm/crud.html#preloading-eager-loading

    【讨论】:

      猜你喜欢
      • 2015-06-08
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多