在 golang 中与 gorm 的一对多关系不起作用
One to many relationship with gorm in golang doesnt work
我有两个 table:
type Person struct {
ID int
FirstName string
LastName string
Functions []Function
}
type Function struct {
gorm.Model
Info string
Person Person
}
我这样创建 table:
db.AutoMigrate(&models.Person{}, &models.Function{})
然后我初始化数据库:
user := models.Person{
FirstName: "Isa",
LastName: "istcool",
Functions: []models.Function{{Info: "Trainer"}, {Info: "CEO"}},
}
db.Create(&user)
现在的问题是我的 Person
table 只得到了 Firstname
和 Lastname
列,而我的 Function
table 只得到了Info
列。
但是当我开始我的 GET
请求时,我得到了列函数始终为空的人。
Here is a screenshot from my GET request and my db
要查看代码,请访问我的 GitHub repo
终于找到答案了!!
问题是我必须使用的 GET 函数
db.Preload("Functions").Find(&[]models.Person{})
而不是
db.Find(&[]models.Person{})
我有两个 table:
type Person struct {
ID int
FirstName string
LastName string
Functions []Function
}
type Function struct {
gorm.Model
Info string
Person Person
}
我这样创建 table:
db.AutoMigrate(&models.Person{}, &models.Function{})
然后我初始化数据库:
user := models.Person{
FirstName: "Isa",
LastName: "istcool",
Functions: []models.Function{{Info: "Trainer"}, {Info: "CEO"}},
}
db.Create(&user)
现在的问题是我的 Person
table 只得到了 Firstname
和 Lastname
列,而我的 Function
table 只得到了Info
列。
但是当我开始我的 GET
请求时,我得到了列函数始终为空的人。
Here is a screenshot from my GET request and my db
要查看代码,请访问我的 GitHub repo
终于找到答案了!! 问题是我必须使用的 GET 函数
db.Preload("Functions").Find(&[]models.Person{})
而不是
db.Find(&[]models.Person{})