gorm golang one2many same table

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

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使这种关系工作吗?

非常感谢! gorm golang one2many same table

英文:

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 gorm golang one2many same table

答案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"`
}

huangapple
  • 本文由 发表于 2017年7月5日 19:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/44924692.html
匿名

发表评论

匿名网友

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

确定