假设我有 3 个表:Houses
has_many Wardrobes
has_many Clothes
。
houses wardrobes clothes
------ --------- -------
id id id
name house_id wardrobe_id
name name
如何,有一个House
我可以选择它Wardrobes
有jeans
和shirt
作为Clothes
?
由于明显原因不起作用的示例代码:
@house.wardrobes.joins(:clothes)
.where("clothes.name = 'jeans'")
.where("clothes.name = 'shirt'")
欢迎任何 SQL/ActiveRecord 答案。
您可以使用聚合来获取同时包含这两种衣物的所有衣柜:
select w.id, w.house_id
from wardrobes w join
clothes c
on c.wardrobe_id = w.id
where c.name in ('jeans', 'shirt')
group by w.id, w.house_id
having count(distinct c.name) = 2;
如果您只想要一所房子,您可以按house_id
in过滤where
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句