gorm golang one2many 相同 table
gorm golang one2many same table
我正在尝试使用 golang gorm 在 (my)sql table 中创建自引用。目前我的代码如下所示:
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")
}
代码失败并出现错误 "reflect.Value.Set using unaddressable value"。
有人知道如何使用 go gorm 使这种关系正常工作吗?
非常感谢:)
幸运的是gorm最近添加了这个功能(参考:here)。
你的情况应该是这样的:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"many2many: children;association_jointable_foreignkey:children_id"`
}
我正在尝试使用 golang gorm 在 (my)sql table 中创建自引用。目前我的代码如下所示:
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")
}
代码失败并出现错误 "reflect.Value.Set using unaddressable value"。
有人知道如何使用 go gorm 使这种关系正常工作吗?
非常感谢:)
幸运的是gorm最近添加了这个功能(参考:here)。
你的情况应该是这样的:
type Person struct {
gorm.Model
Name string
Children []*Person `gorm:"many2many: children;association_jointable_foreignkey:children_id"`
}