Gorm Manytomany:按照Manytomany协会的条件滤波记录

发布于 2025-01-22 05:39:23 字数 1238 浏览 0 评论 0原文

考虑以下数据结构:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文