在简单的多对多关系上使用超级简单的 Gorm 查询时遇到问题,我在 MYSQL 数据库中有 3 个表,建模如下:
type Product struct {
ID uint `gorm:"unique" json:"id"`
Name string `gorm:"name" json:"name"`
Ingredients []Ingredient `gorm:"many2many:product_ingredients;" json:"ingredients"`
}
type Ingredient struct {
ID uint `gorm:"unique" json:"id"`
Name string `gorm:"name" json:"name"`
}
Run Code Online (Sandbox Code Playgroud)
(和一个连接表)
我想要一个查询来获取特定产品中包含该成分的所有产品:
我可以得到所有数据的一般查询:
db.Debug().Preload("Ingredients").Limit(limit).Offset(offset).Find(&products)
Run Code Online (Sandbox Code Playgroud)
但尝试做这样的事情
db.Debug().Preload("Ingredients").Limit(limit).Offset(offset).Where(Ingredient{Name: "Chicken"}).Find(&products)
Run Code Online (Sandbox Code Playgroud)
给我错误 1054:“where 子句”中的未知列“ingredients.name”
我希望只退回含有鸡肉成分的产品。
有人能帮忙吗?
这应该相当简单,但我找不到任何这样的用例,而且文档非常混乱。
| 归档时间: |
|
| 查看次数: |
675 次 |
| 最近记录: |