duanpu8830 2017-07-05 11:13
浏览 84
已采纳

gorm golang one2many同一张桌子

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条回答 默认 最新

  • doulang5323 2018-02-15 12:17
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作