【问题标题】:How can I go about making a many2many relationship to self in golang gorm?我怎样才能在golang gorm中与self建立many2many关系?
【发布时间】:2015-02-24 16:41:15
【问题描述】:

我有一个 psql 数据库,我正在使用 gorm 库以及 pq 驱动程序,正如您所见,相关产品存在多对多关系,但是这会抛出错误 pq: column "product_id" specified more than once 有没有办法设置别名还是我做错了?

type Product struct {
    Id          int64      `json:"_id"`
    Price       float32    `json:"price"`
    Name        string     `sql:"size:255" json:"name"`
    Description string     `json:"description"`
    Material    string     `json:"material"`
    Color       string     `json:"color"`
    ColorId     int64      `json:"colorId"`
    Categories  []Category `gorm:"many2many:product_categories;" json:"categories"`
    Images      []Image    `json:"images"`
    Tags        []Tag      `gorm:"many2many:product_tags;" json:"tags"`
    Main        bool       `json:"main"`
    Available   bool       `json:"available"`
    Slug        string     `json:"slug"`
    CreatedAt   time.Time  `json:"createdAt"`
    Related     []Product  `gorm:"many2many:related_products;" json:"related"`
}

【问题讨论】:

    标签: go psql go-gorm


    【解决方案1】:

    我找到了自引用 many2many 关系的解决方案。 :D

    type User struct {
        Id int64
        Related     []Product  `gorm:"foreignkey:product_id;associationforeignkey:related_product_id;many2many:related_products;" json:"related"`        
    }
    

    【讨论】:

    • 我认为你的意思是“type Product struct { ...”但是我尝试了这个解决方案,但是当我调用“db.Save(&myProduct)”时,什么都不会添加到related_products 和related_products 只会一列名为 product_id 的列似乎不正确,related_product_id 在哪里?!
    • 这可能在过去的某个时候有效,但不适用于任何最新版本。请参阅此拉取请求,了解已测试可与最新版本一起使用的可能解决方案:github.com/jinzhu/gorm/pull/1709
    【解决方案2】:

    有点旧的帖子,但幸运的是 gorm 最近添加了此功能(参考:here)。

    你的情况应该是这样的:

    type Product struct {
      Id          int64      `json:"_id"`
      .
      .
      .
      Related     []Product `gorm:"many2many:related_products;association_jointable_foreignkey:related_id"`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多