【问题标题】:Rails: find all parents with all children having a particular attributeRails:查找所有具有特定属性的孩子的所有父母
【发布时间】:2019-04-11 18:33:53
【问题描述】:

我需要找到所有具有状态 = 1 的孩子的父母。

如果其中一个孩子不是status = 1;则未选择父级。

class Parent
  has_many :children
end

class Child
  status = [ 0, 1 ]
end

这个我试过了,还是不行。

Parent.left_outer_joins(:children).where("children.status = ?", 1)

它不起作用,因为我仍然得到 Parent with children status=0

【问题讨论】:

  • it doesn't work. 是什么意思您在查询时遇到任何错误或问题吗?
  • @Gabbar 它不起作用,因为我仍然得到 Parent with children status=0
  • status 枚举?
  • @Gabbar 是的,它是枚举
  • 我猜在你的情况下加入是不够的。 “所有孩子的状态为 1”等价于“没有状态为 0 的孩子”。因此,您需要像select * from parents p where not exists (select 1 from children c where c.parent_id = p.id and status = 0) 这样的查询——不确定是否可以使用 AR 查询界面构建它。 AREL 魔法可能会有所帮助,但老实说,在实践中我更喜欢纯 SQL - 因为更具可读性和直截了当......

标签: ruby-on-rails ruby activerecord


【解决方案1】:

试试这个:

Parent.where("id NOT IN (SELECT DISTINCT(parent_id) FROM children WHERE children.status =1)")

希望对您有所帮助!!!

【讨论】:

    【解决方案2】:

    我认为你需要一个子查询:

    Parent.where.not(id: Children.where.not(status: 1).select(:parent_id))
    

    【讨论】:

    • 我刚刚更新了我的答案,因为它不正确。请随意尝试这个:))
    【解决方案3】:

    我认为你可以这样做:

    Parent.joins(:children).where.not(
      id: Child.where(status: :closed).select('DISTINCT "parent_id"')
    ).distinct
    

    【讨论】:

    • 但是,这不仅仅向父母显示 所有 的孩子都关闭的位置。如果 任何 个子节点已关闭,它将在此处显示父节点。
    猜你喜欢
    • 1970-01-01
    • 2015-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多