假设我有嵌套结构,如
Resource A
-id
Resource B
-id
-a_id
Resource C
-id
-b_id
Resource D
-id
-c_id
给定a_id我想在一个查询中抓取所有D,如:
SELECT *
FROM D
JOIN C on c_id
JOIN B on b_id
WHERE B.a_id = a_id
我知道我可以内联这个SQL,但我想知道是否有办法用ActiveRecord关系来做这个?
答案 0 :(得分:1)
class A < ActiveRecord::Base
hash_many :bs
end
class B < ActiveRecord::Base
belongs_to :a
has_many :cs
end
class C < ActiveRecord::Base
belongs_to :b
has_many :ds
end
class D < ActiveRecord::Base
belongs_to :c
end
C.joins(:c => :b).where(:b => {:a_id => <given_a_id>})
答案 1 :(得分:0)
在active_record文档中找到答案。
D.joins(C: :B).where(B: { a_id: a_id})