什么是mongoid / ruby语法:
我想查询Parent
,包括所有Children
(急切地)搜索某个唯一的Child
属性(不是_id
)。
class Parent
include Mongoid::Document
field :first_name, :type => String
field :last_name, :type => String
has_many :children, :class_name => 'Child', :inverse_of => :parent
end
class Child
include Mongoid::Document
field :first_name, :type => String
field :last_name, :type => String
belongs_to :parent, :class_name => 'Parent', :inverse_of => :children
end
在SQL中,我会写
SELECT p.*, c.*
FROM Parent p
INNER JOIN Child c
ON c.parent_id = p._id
WHERE EXISTS (
SELECT 1 FROM Child c2 WHERE c2.first_name = 'Aaron' AND c2.parent_id = p._id
);
答案 0 :(得分:1)
试试这个
children = Child.where(:first_name => "Aaron")
children.each do |child|
parent = child.parent
end
如果您只需要基于上述条件的发布详细信息,则可以运行此
Parent.includes(:child).where('child.first_name' => "Aaron")
但是对于孩子,你必须再次进行查询。