猿问

我怎样才能在 golang gorm 中与 self 建立多对多的关系?

我有一个 psql 数据库,我正在使用 gorm 库和 pq 驱动程序,如您所见,相关产品存在多对多关系,但是这会抛出错误 pq: column "product_id" specified more than once是否有设置别名或 am 的方法我以错误的方式解决这个问题?


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

}


智慧大石
浏览 246回答 2
2回答

海绵宝宝撒

我找到了自引用多对多关系的解决方案。:Dtype User struct {    Id int64    Related     []Product  `gorm:"foreignkey:product_id;associationforeignkey:related_product_id;many2many:related_products;" json:"related"`        }

catspeake

有点老帖子但幸运的是 gorm 最近添加了这个功能(参考:这里)。在你的情况下应该是这样的:type Product struct {  Id          int64      `json:"_id"`  .  .  .  Related     []Product `gorm:"many2many:related_products;association_jointable_foreignkey:related_id"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答