2014-07-02 42 views
2

我正在尝试查找与我的Person,自加入,记录及其所有子元素相关的所有朋友。获取自加入对象及其子元素上的所有关联对象

这是我试图运行的一个示例。我有一个人的记录,让我们叫它@person,有4个'孩子'。

这些孩子都有很多朋友。

当我查询@person时,我希望自己的所有朋友,然后是它下面的四个孩子。

有没有办法做到这一点没有去:friends = @parent.friends + @parent.children.map {|c| c.friends }

真的很喜欢用一个数据库查询来做到这一点。我的数据库也是postgresql。

这里是我的记录如何设置的例子。

class Person < ActiveRecord::Base 

    belongs_to :parent, :class_name => "Person", :foreign_key => "parent_person_id" 
    has_many :children, :class_name => "Person", :foreign_key => "parent_person_id" 
    has_many :friends 

end 

class Friend < ActiveRecord::Base 
    belongs_to :person 
end 
+0

对于孩子,foregin键应该是'id'而不是'paren t_person_id' –

+0

@arivarasan - 它的工作原理是如何设置的。我绝对能够找到孩子和记录的父母。我记录中的字段是:'id:integer,parent_genre_id:integer,title:string,created_at:datetime,updated_at:datetime'。 –

回答

3

至于儿童,你foreign_key必须ID

has_many :children, :class_name => "Person", :foreign_key => "id" 

试试这个:

people_ids = @parent.children.map(&:id).push(@parent.id) 
Friend.where(person_id: people_ids) 

或者你可以渴望的负载关联的表是这样的:

friends = Person.includes(:friends).where("parent_person_id = ? or id = ?", [@parent.id, @parent.id]).map(&friends) 
+0

感谢您的回答。我知道我可以抓住所有孩子的身份证来做类似于你的回答的事情。我可以用两个数据库查询来做到这一点,而不是使用'.pluck(:id)'将所有记录拖入ruby。任何想法如何将你的两个数据库查询合并为一个? –

+0

好吧,尝试加载,像Person.includes(:friends).where(id:people_ids)这样的东西,我不认为你可以消除调用子查询寿。 –

+0

为什么不考虑使用像MongoDB这样的NoSQL DB,你将能够将数据嵌入到Person表中,并且需要不断的时间来查询结果? –

1

祖先

你为什么不看ancestry gem

这基本上允许你在你的模型中定义children而不必定义关联(从而防止不必要的查询)。你就可以做到这一点是这样的:

#app/models/person.rb 
Class Person < ActiveRecord::Base 
    has_ancestry 
end 

宝石会在您的表,你可以用“子”对象来填充一个ancestry柱:

enter image description here

这可以让你选择模型的children这样的:

@person = Person.find params[:id] 
@person.children.each do |child| 
    child.name 
end 

这里有各种方法has_ancestry追加到y我们model

enter image description here

-

买者

一个警告的情况是,如果你想多嵌套项目,你需要使用父母组整个树就像我们上面的例子:

parent_id_1/parent_id_2 
+1

是的,我看了看那个家伙。我目前所需要的是过度杀伤力。截至目前,确实只有父母和孩子的一级。不过肯定会记住它! –

相关问题