如何使用GORM在多对多关系中联接两个表?

时间:2019-10-25 04:52:46

标签: postgresql go go-gorm

我在“产品”和“类别”表之间存在多对多关系。我想检索所有带有其类别的产品。

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

bellow代码返回categorie_id 3的所有产品,但这些产品的Categories切片为空

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

1 个答案:

答案 0 :(得分:0)

得到解决方案

class ParticipantID(code:String, value:String) {

@JacksonXmlProperty(isAttribute = true)
private var code:String = code
    get() = field

@JacksonXmlText
private var value:String = value
    get() = field

这将返回所有产品及其类别。