我有两个表:
type Person struct {
ID int
FirstName string
LastName string
Functions []Function
}
type Function struct {
gorm.Model
Info string
Person Person
}
我这样创建表格:
db.AutoMigrate(&models.Person{}, &models.Function{})
然后我初始化数据库:
user := models.Person{
FirstName: "Isa",
LastName: "istcool",
Functions: []models.Function{{Info: "Trainer"}, {Info: "CEO"}},
}
db.Create(&user)
现在的问题是我的 Person
表只有 Firstname
和 Lastname
列,而我的 Function
表只有得到 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{})
关于mysql - 在 golang 中与 gorm 的一对多关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41505884/