轨道4的范围找父母,没有孩子轨道、范围、父母、孩子

2023-09-08 15:39:49 作者:哽咽一句 我想你了

我发现一个答案说了一些有用的例子寻找父母 N 的孩子,但同样不是找父母没有子女可用(presumably自加盟排除它们)。

I found one answer that had some usable having examples for finding parents with n children, but the same is not usable for finding parents with no children (presumably since the join excludes them).

scope :with_children, joins(:children).group("child_join_table.parent_id").having("count(child_join_table.parent_id) > 0")

任何人都可以点我朝着正确的方向?

Can anyone point me in the right direction?

推荐答案

这应该做你想要的工作:

This should do the job you want:

scope :without_children, includes(:children).where(:children => { :id => nil })

这里最大的区别是加入成为包括:一个包括加载所有关系,如果他们存在,连接只会加载关联对象,而忽略对象没有关系。

The big difference here is the joins becoming a includes: an include loads all the relations, if they exists, the join will load only the associated objects and ignore the object without a relation.

其实,范围:with_children,加入(:儿童)应该是刚够至少有1名儿童返回父。试试吧!

In fact, scope :with_children, joins(:children) should be just enough to return the Parent with at least 1 child. Try it out!

由于@MauroDias指出,如果这是你的父母和孩子,这code以上将无法正常工作的一种自我指涉的关系

As @MauroDias pointed out, if it is a self-referential relationship between your parent and children, this code above won't work.

随着研究一点点,我发现了如何做到这一点:

With a little bit of research, I found out how to do it:

考虑这个模型:

class Item < ActiveRecord::Base
  has_many :children, :class_name => 'Item', :foreign_key => 'parent_id'

如何返回,没有子女的所有项目:

How to return all items with no child(ren):

Item.includes(:children).where(children_items: { id: nil })

我是怎么找到 children_items 表?

Item.joins(:儿童)生成的SQL语句:

SELECT "items".* 
FROM "items" 
 INNER JOIN "items" "children_items" 
 ON "children_items"."parent_id" = "items"."id"

所以我猜Rails使用的表需要在自我指涉的情况下,JOIN的时候。

So I guessed that Rails uses a table when in need of a JOIN in a self-referential case.

类似的问题:

How查询一个模式的基础上,属于所述第一模型的另一模型的属性?中 Rails与活动记录查询协会'存在' Rails 3,HAS_ONE /的has_many与拉姆达条件 Join与活跃记录多个表 How to query a model based on attribute of another model which belongs to the first model? Rails active record querying association with 'exists' Rails 3, has_one / has_many with lambda condition Join multiple tables with active records