我的產(chǎn)品和類別表之間有多對(duì)多關(guān)系。我想檢索所有產(chǎn)品及其類別。type Product struct { ProductID int `gorm:"column:product_id;primary_key" json:"product_id"` Name string `gorm:"column:name" json:"name"` Description string `gorm:"column:description" json:"description"` Categories []Category `gorm:"many2many:product_category;foreignkey:product_id;association_foreignkey:category_id;association_jointable_foreignkey:category_id;jointable_foreignkey:product_id;"`}type Category struct { CategoryID int `gorm:"column:category_id;primary_key" json:"category_id"` Name string `gorm:"column:name" json:"name"` Description null.String `gorm:"column:description" json:"description"` Products []Product `gorm:"many2many:product_category;foreignkey:category_id;association_foreignkey:product_id;association_jointable_foreignkey:product_id;jointable_foreignkey:category_id;"`}下面的代碼返回categorie_id 3的所有產(chǎn)品,但這些產(chǎn)品的類別切片為空var products []model.Productcat := model.Category{}s.db.First(&cat, "category_id = ?", 3)err := s.db.Model(&cat).Related(&products, "Products").Error我嘗試了以下代碼,但沒有返回任何內(nèi)容var products []model.Productvar cat [] model.Categoryerr := s.db.Model(&cat).Related(&products, "Products").Error
1 回答

米脂
TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超3個(gè)贊
得到了解決方案
products := []*model.Product{} DB.Preload("Categories").Find(&products)
這將返回所有產(chǎn)品及其類別。
- 1 回答
- 0 關(guān)注
- 142 瀏覽
添加回答
舉報(bào)
0/150
提交
取消