如何使用GORM从具有多对多关系的其他表中过滤带有实体的表?

问题描述 投票:0回答:1

我有使用多对多关系与其他两个表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;"`
}

如果我想按类别查询产品表,我可以像下面这样进行操作,它将返回类别为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表,该怎么办?假设我要查找所有类别为category_id 3且AttributeValue为attribute_value_id 2的产品?

sql go gorm go-gorm
1个回答
0
投票

我发现了一些根据类别和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)

执行此操作后,产品切片将填充类别类别为3且属性值为属性值为2的所有产品。如果需要在多个类别和属性值中查找产品,可以传递字符串切片。

© www.soinside.com 2019 - 2024. All rights reserved.