gorm golang one2many same table

2019-08-18 03:52发布

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 :)

标签: go go-gorm
1条回答
爷的心禁止访问
2楼-- · 2019-08-18 04:14

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"`
}
查看更多
登录 后发表回答