如何使用 GORM 从多对多关系相关的其他表中过滤包含实体的表?

我有 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 的类别的所有产品?


不负相思意
浏览 94回答 1
1回答

炎炎设计

我找到了一些根据类别和 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)执行此操作后,产品切片将填充属于类别 ID 为 3 且 AttributeValue 为 attribute_value_id 2 的所有产品。如果我们需要在多个类别和属性值中查找产品,我们可以传递字符串切片。
打开App,查看更多内容
随时随地看视频慕课网APP