这适用于使用 PostgreSQL 的 Rails 5/Active Record 5。
假设我有两个模型:Product
和 Widget
. A Product
has_many
小部件和 Widget
has_many
通过名为 products_widgets
的连接表获得产品.
我想编写一个查询来查找与带有 id=37
的小部件关联的所有产品。和带有 id=42
的小部件.
我实际上有一个 id 列表,但是如果我能写出上面的查询,我一般可以解决这个问题。
请注意,此查询的更简单版本是查找与带有 id=37
的小部件关联的所有小部件。或带有 id=42
的小部件,你可以这样写:Product.joins(:products_widgets).where(products_widgets: {widget_id: [37, 42]})
但这不是我需要的。
最佳答案
首先:在纯 SQL 中,您可以使用 exists
来表达查询。状况:
select p.*
from product p
where
exists (
select 1
from products_widgets pw
where pw.product_id = p.product_id and pw.widget_id = 37
)
and exists (
select 1
from products_widgets pw
where pw.product_id = p.product_id and pw.widget_id = 42
)
在事件记录中,我们可以尝试直接使用
where
中的原始子查询。状况:product
.where('exists(select 1 from products_widgets where product_id = product.product_id and widget_id = ?)', 37)
.where('exists(select 1 from products_widgets where product_id = product.product_id and widget_id = ?)', 42)
我认为使用
.arel.exist
也可能有效:product
.where(products_widgets.where('product_id = product.product_id and widget_id = ?', 37).arel.exists)
.where(products_widgets.where('product_id = product.product_id and widget_id = ?', 42).arel.exists)
关于ruby-on-rails - 使用带有事件记录的连接表时如何连接模型的多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61828113/