我的产品和类别表之间有多对多关系。我想检索所有产品及其类别。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的所有产品,但这些产品的类别切片为空var products []model.Productcat := model.Category{}s.db.First(&cat, "category_id = ?", 3)err := s.db.Model(&cat).Related(&products, "Products").Error我尝试了以下代码,但没有返回任何内容var products []model.Productvar cat [] model.Categoryerr := s.db.Model(&cat).Related(&products, "Products").Error
1 回答
米脂
TA贡献1836条经验 获得超3个赞
得到了解决方案
products := []*model.Product{} DB.Preload("Categories").Find(&products)
这将返回所有产品及其类别。
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报
0/150
提交
取消