gorm golang one2many同一张桌子 [英] gorm golang one2many same table

查看:96
本文介绍了gorm golang one2many同一张桌子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用golang gorm在(my)sql表中创建自引用.目前,我的代码如下:

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

代码失败,并显示错误"reflect.Value.Set使用不可寻址的值".

The code is failing with an error "reflect.Value.Set using unaddressable value".

有人知道如何使用go gorm建立这种关系吗?

Does anybody know how to get this relationship working using go gorm?

非常感谢:)

推荐答案

最近,gorm添加了此功能(参考:此处).

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

这篇关于gorm golang one2many同一张桌子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆