gorm golang one2many 同一张表

标签 go go-gorm

我正在尝试使用 golang gorm 在(我的)sql 表中创建一个自引用。目前我的代码如下所示:

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

关于gorm golang one2many 同一张表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44924692/

相关文章:

go - 结构类型作为映射键

mysql - 外键和相关数据与 gorm

postgresql - Gorm卡在gorm.Open上,没有报错但是没有反应

go - 如何构造SELECT * FROM (<subquery>) ORDER BY column;形式的子查询?

gorm 多对一返回空

json - Golang Gorm 使用 slices 和 postgres 的 json 字段

pointers - golang 中的 Null 与 nil?

go - 在浏览器中本地查看包文档

go - 如何解析变量的副本而不是指针?

inheritance - Go 中创建复杂结构层次结构的惯用方法是什么?