1

所以我知道如何找到所有没有子记录的父记录。

Parent.joins(:child).where(child: {id: nil})

但是,如何找到过去 30 天内没有创建子项的所有父记录。我尝试了以下但没有用

Parent.joins(:child).where(child: {id: nil, created_at: 30.days.ago...Time.current})
Parent.joins(:child).where(child: {created_at: 30.days.ago...Time.current).where(child: {id: nil})

他们都没有工作。有任何想法吗?

4

2 回答 2

2

你应该能够使用where.not这个:

更新:即使没有孩子也要获取所有记录,请使用left_outer_joins

# from: 
# Parent.joins(:child).where.not(child: { created_at: 30.days.ago...Time.current } )
# to:
Parent.left_outer_joins(:child).where.not(child: { created_at: 30.days.ago...Time.current } )

它非常不言自明,绘制了所有不符合标准的记录。

为了解释 和 之间的区别joinsleft_outer_joins我将使用另一个问题的引用,因为他们的解释是完美的:

INNER JOIN:当两个表都匹配时返回行。

LEFT JOIN:返回左表中的所有行,即使右表中没有匹配项。

因此,您需要后者以包含没有子项的父记录。

希望它有所帮助 - 让我知道您的进展情况或如果您有任何问题 :)

于 2019-09-25T19:01:05.213 回答
2

您将需要内部查询来做您想做的事。一种方法:

Parent.where.not(id: Parent.joins(:child).where(child: { created_at: 30.days.ago...Time.current }).pluck(:id).uniq)

这将选择所有在 30 天内没有孩子的父母。希望这有帮助。

编辑:

它可以分为两个简单的查询:

unwanted_parents_ids = Parent.joins(:child).where(child: { created_at: 30.days.ago...Time.current }).pluck(:id).uniq
wanted_parents = Parent.where.not(id: unwanted_parents_ids)
于 2019-09-26T07:21:32.647 回答