Gorm Manytomany:按照Manytomany协会的条件滤波记录
考虑以下数据结构:
type Foo struct {
FooID int64 `gorm:"primaryKey;column:foo_id"`
FooBars []*FooBar `gorm:many2many:"foo_bar_map;foreignKey:foo_id;joinForeignKey:foo_id;references:bar_id;joinReferences:bar_id"`
}
type Bar struct {
BarID int64 `gorm:"primaryKey;column:bar_id"`
FooBars []*FooBar `gorm:"many2many:foo_bar_map;foreignKey:bar_id;joinForeignKey:bar_id;references:foo_id;joinReferences:foo_id"`
}
type FooBarMap struct {
FooID int64 `gorm:"primaryKey;column:foo_id"`
BarID int64 `gorm:"primaryKey;column:bar_id;"`
Foo *Foo `gorm:"foreignKey:foo_id;references:foo_id"`
Bar *Bar `gorm:"foreignKey:bar_id;references:bar_id"`
}
现在我要进行的查询是:
DB.Model(Foo{}).Preload("FooBars", "bar_id in ?", [1,2]).Find(&foos)
基本上我只想加载与bar
1,2 1,2相同的foos
。 t过滤记录,因为条件变为以下类似:
...where bar_id in (1,2,3,4,5 ..all the mappings available) and bar_id in [1,2]
update
我能够像以下那样解决此问题:
.Joins("INNER JOIN foo_bar_map on foo_bar_map.foo_id = foo.foo_id and foo_bar_map.foo_id in (?)", [1,2])
有没有更好的方法来创建此查询,我正在寻找避免使用的方法代码中的直接DB列名称。
Consider below data structure:
type Foo struct {
FooID int64 `gorm:"primaryKey;column:foo_id"`
FooBars []*FooBar `gorm:many2many:"foo_bar_map;foreignKey:foo_id;joinForeignKey:foo_id;references:bar_id;joinReferences:bar_id"`
}
type Bar struct {
BarID int64 `gorm:"primaryKey;column:bar_id"`
FooBars []*FooBar `gorm:"many2many:foo_bar_map;foreignKey:bar_id;joinForeignKey:bar_id;references:foo_id;joinReferences:foo_id"`
}
type FooBarMap struct {
FooID int64 `gorm:"primaryKey;column:foo_id"`
BarID int64 `gorm:"primaryKey;column:bar_id;"`
Foo *Foo `gorm:"foreignKey:foo_id;references:foo_id"`
Bar *Bar `gorm:"foreignKey:bar_id;references:bar_id"`
}
Now the query I want to make is:
DB.Model(Foo{}).Preload("FooBars", "bar_id in ?", [1,2]).Find(&foos)
Basically I want to load only those Foos
which are associated with Bar
1,2
this exact same query doesn't filter the records, because where condition becomes something like below:
...where bar_id in (1,2,3,4,5 ..all the mappings available) and bar_id in [1,2]
UPDATE
I've been able to solve this like below:
.Joins("INNER JOIN foo_bar_map on foo_bar_map.foo_id = foo.foo_id and foo_bar_map.foo_id in (?)", [1,2])
Is there a better way of creating this query, I am looking for ways to avoid using direct db column names in the code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论