在golang中,使用gorm建立一对多关系无法正常工作。

huangapple go评论84阅读模式
英文:

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表只有FirstnameLastname列,而我的Function表只有Info列。
但是当我发起GET请求时,我得到的人员的function列始终为空。

这是我发起GET请求和我的数据库的截图

要查看代码,请访问我的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{})

huangapple
  • 本文由 发表于 2017年1月6日 20:35:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41505884.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定