英文:
One to many relationship with gorm in golang doesnt work
问题
我有两个表:
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
请求时,我得到的人员的function
列始终为空。
要查看代码,请访问我的GitHub存储库。
英文:
I have two tables:
type Person struct {
ID int
FirstName string
LastName string
Functions []Function
}
type Function struct {
gorm.Model
Info string
Person Person
}
I create the tables like this:
db.AutoMigrate(&models.Person{}, &models.Function{})
I then initialize the database:
user := models.Person{
FirstName: "Isa",
LastName: "istcool",
Functions: []models.Function{{Info: "Trainer"}, {Info: "CEO"}},
}
db.Create(&user)
Now the problem is that my Person
table only got Firstname
and Lastname
columns and my Function
table only got the Info
column.
But when I start my GET
request I get people with the column function which is always null.
Here is a screenshot from my GET request and my db
To see the code visit my GitHub repo
答案1
得分: 6
终于找到答案了!问题出在我的GET函数上,我需要使用以下代码:
db.Preload("Functions").Find(&[]models.Person{})
而不是:
db.Find(&[]models.Person{})
英文:
Finally found the answer!!
The problem is my GET functions I have to use
db.Preload("Functions").Find(&[]models.Person{})
instead of
db.Find(&[]models.Person{})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论