我有一個 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"`
}

catspeake
TA貢獻1111條經驗 獲得超0個贊
有點老帖子但幸運的是 gorm 最近添加了這個功能(參考:這里)。
在你的情況下應該是這樣的:
type Product struct {
Id int64 `json:"_id"`
.
.
.
Related []Product `gorm:"many2many:related_products;association_jointable_foreignkey:related_id"`
}
- 2 回答
- 0 關注
- 216 瀏覽
添加回答
舉報
0/150
提交
取消