【问题标题】:Proper way of selecting related objects by multiple rows多行选择相关对象的正确方法
【发布时间】:2019-05-23 15:18:25
【问题描述】:

假设我有 3 张桌子:Houseshas_many Wardrobeshas_many Clothes

houses    wardrobes   clothes
------    ---------   -------
id        id          id
name      house_id    wardrobe_id
          name        name

怎么样,有一个House 我可以选择它的Wardrobesjeansshirt 作为Clothes

由于明显原因而无法工作的示例代码:

@house.wardrobes.joins(:clothes)
  .where("clothes.name = 'jeans'")
  .where("clothes.name = 'shirt'")

欢迎任何 SQL/ActiveRecord 答案。

【问题讨论】:

    标签: sql ruby-on-rails ruby postgresql


    【解决方案1】:

    您可以使用聚合来获取同时拥有这两种衣服的所有衣柜:

    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;
    

    如果您只想为一所房子提供此信息,您可以按where 中的house_id 进行过滤。

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      相关资源
      最近更新 更多