亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我怎樣才能在 golang gorm 中與 self 建立多對多的關系?

我怎樣才能在 golang gorm 中與 self 建立多對多的關系?

Go
智慧大石 2021-09-10 15:33:43
我有一個 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"`}
查看完整描述

2 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

我找到了自引用多對多關系的解決方案。:D


type User struct {

    Id int64

    Related     []Product  `gorm:"foreignkey:product_id;associationforeignkey:related_product_id;many2many:related_products;" json:"related"`        

}


查看完整回答
反對 回復 2021-09-10
?
catspeake

TA貢獻1111條經驗 獲得超0個贊

有點老帖子但幸運的是 gorm 最近添加了這個功能(參考:這里)。


在你的情況下應該是這樣的:


type Product struct {

  Id          int64      `json:"_id"`

  .

  .

  .

  Related     []Product `gorm:"many2many:related_products;association_jointable_foreignkey:related_id"`

}


查看完整回答
反對 回復 2021-09-10
  • 2 回答
  • 0 關注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號