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

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

波纹管代码返回categorie_id 3的所有产品,但是这些产品的类别 slice 为空
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

最佳答案

得到了解决方案

products := []*model.Product{}
DB.Preload("Categories").Find(&products)

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

关于postgresql - 如何使用GORM在多对多关系中联接两个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58552373/

相关文章:

postgresql - 我在安装 pg admin 时忘记配置登录电子邮件 ID 和密码 4. 安装后如何更改

mysql - 对嵌套的外键关系执行 SUM

python - 将字符串列表传递给原始 sql 查询(Python/Django)

go - 合并排序计数器 slice

go - 处理动态子域

go - 从某个 channel 接收到无处可去的地方

去建立错误 "db.GetUsers undefined (type *gorm.DB has no field or method GetUsers)"

sql - 外键死锁如何删除记录?

sql - golang gorm 多对多反向引用

GORM 在调用 Updates() 时更新空字段?