我的产品和类别表之间有多对多关系。我想检索所有产品及其类别。
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.Product
cat := model.Category{}
s.db.First(&cat, "category_id = ?", 3)
err := s.db.Model(&cat).Related(&products, "Products").Error
我尝试了以下代码,但没有返回任何内容
var products []model.Product
var cat [] model.Category
err := s.db.Model(&cat).Related(&products, "Products").Error
米脂
相关分类