英文:
gorm golang one2many same table
问题
我正在尝试使用Golang GORM在MySQL表中创建自引用。目前我的代码如下:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"ForeignKey:ParentID"`
ParentID uint
}
func main() {
/* 省略获取数据库连接的代码 */
p := &Person{Name: "Sally"}
db.Create(p)
children := []*Person{
{Name: "Jane", ParentID: p.ID},
{Name: "Tom", ParentID: p.ID},
}
for _, child := range children {
db.Create(child)
}
var children2 []*Person
db.Model(p).Related(&children2, "ParentID")
}
代码出现错误"reflect.Value.Set using unaddressable value"。
有人知道如何使用Go GORM使这种关系工作吗?
非常感谢!
英文:
I'm trying to create a self-reference in a (my)sql table using golang gorm. At the moment my code looks like this:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"ForeignKey:ParentID"`
ParentID uint
}
func main() {
/* code to get database connection omitted */
p := &Person{Name:"Sally"}
db.Create(p)
children := []*Person{ {Name:"Jane", ParentID:p.ID},
{Name:"Tom", ParentID:p.ID}}
for _, child := range children {
db.Create(child)
}
var children2 []*Person
db.Model(p).Related(children2, "ParentID")
}
The code is failing with an error "reflect.Value.Set using unaddressable value".
Does anybody know how to get this relationship working using go gorm?
Many thanks in advance
答案1
得分: 2
幸运的是,gorm最近添加了这个功能(参考:这里)。
在你的情况下应该是这样的:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"many2many:children;association_jointable_foreignkey:children_id"`
}
英文:
Fortunately gorm have added lately this feature (reference: here).
In your case should be like this:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"many2many: children;association_jointable_foreignkey:children_id"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论