gorm golang one2many same table

孤人 提交于 2020-01-11 11:31:50

问题


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:


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


来源:https://stackoverflow.com/questions/44924692/gorm-golang-one2many-same-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!