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 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持