我有 Product 表,它使用多对多关系与其他两个表 Category & AttributeValue 连接。我使用 GORM 作为 ORM。这些表的 go 结构如下所示。
type Product struct {
ProductID int `gorm:"column:product_id;primary_key" json:"product_id"`
Name string `gorm:"column:name" json:"name"`
Categories []Category `gorm:"many2many:product_category;foreignkey:product_id;association_foreignkey:category_id;association_jointable_foreignkey:category_id;jointable_foreignkey:product_id;"`
AttributeValues []AttributeValue `gorm:"many2many:product_attribute;foreignkey:product_id;association_foreignkey:attribute_value_id;association_jointable_foreignkey:attribute_value_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"`
Products []Product `gorm:"many2many:product_category;foreignkey:category_id;association_foreignkey:product_id;association_jointable_foreignkey:product_id;jointable_foreignkey:category_id;"`
}
type AttributeValue struct {
AttributeValueID int `gorm:"column:attribute_value_id;primary_key" json:"attribute_value_id"`
AttributeID int `gorm:"column:attribute_id" json:"attribute_id"`
Value string `gorm:"column:value" json:"value"`
Products []Product `gorm:"many2many:product_attribute;foreignkey:attribute_value_id;association_foreignkey:product_id;association_jointable_foreignkey:product_id;jointable_foreignkey:attribute_value_id;"`
}
如果我想按类别查询产品表,我可以像下面这样做,它将返回类别 ID 为 3 的类别中的所有产品。
cat := model.Category{}
s.db.First(&cat, "category_id = ?", 3)
products := []*model.Product{}
s.db.Model(&cat).Related(&products, "Products")
如果我想按类别和属性值查询产品表,我该怎么做?假设我想查找属于category_id 3 且AttributeValue 为attribute_value_id 2 的类别的所有产品?
炎炎设计
相关分类