我有使用多对多关系与其他两个表Categorie&AttributeValue连接的Product表。我正在使用GORM作为ORM。那些表的结构就像波纹管一样。

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;"`
}

如果我想按类别查询产品表,可以像波纹管一样进行操作,它将返回category_id 3类别中的所有产品。
cat := model.Category{}
s.db.First(&cat, "category_id = ?", 3)
products := []*model.Product{}
s.db.Model(&cat).Related(&products, "Products")

如果我想同时按Category和AttributeValue查询Product表,该怎么办?假设我要查找所有类别类别为id_id 3并具有AttributeValue和attribute_value_id 2的产品?

最佳答案

我发现了一些根据类别和AttributeValue查询产品的方法。我得到的最好的方式是像波纹管

    products := []*model.Product{}

    s.db.Joins("INNER JOIN product_attribute ON product_attribute.product_id = " +
                    "product.product_id AND product_attribute.attribute_value_id in (?)", 2).
    Joins("INNER JOIN product_category ON product_category.product_id = " +
                    "product.product_id AND product_category.category_id in (?)", 3).
    Find(&products)

执行完此操作后,产品 slice 将填充所有类别中具有category_id 3并具有AttributeValue和attribute_value_id 2的产品。如果需要在多个Category&AttributeValue中查找产品,则可以传递字符串 slice 。

08-06 16:45