正常的铁路集合急切加载的方式如下:
Person.find(:all, :include=>:companies)
这会生成一些
的sqlLEFT OUTER JOIN companies ON people.company_id = companies.id
但是,我需要一个自定义联接(如果我使用find_by_sql
也会出现这种情况),所以我不能使用香草:include => :companies
自定义连接/ sql将获取我需要的所有数据,但是如何告诉activerecord它属于关联的Company
对象而不仅仅是一堆额外的行?
我需要在连接中添加其他条件。像这样:
SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL
<Several other joins>
WHERE blahblahblah
答案 0 :(得分:7)
您是否可以使用ActiveRecord添加连接条件?
例如,我有一个非常复杂的查询使用几个相关记录,它通过组合条件和包含指令工作正常
Contractors.find(
:all,
:include => {:council_areas => :suburbs},
:conditions => ["suburbs.postcode = ?", customer.postcode]
)
假设:
此联接返回由 customer.postcode 标识的郊区的承包商。
生成的查询如下所示:
SELECT contractors.*, council_areas.*, suburbs.*
FROM `contractors`
LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id
LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id
LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id
LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')
(注意:为简洁起见,我编辑了列表。)
答案 1 :(得分:3)
您可以使用以下内容来获得适当的左外连接语法魔法。
Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'
答案 2 :(得分:2)
我不确定这是你想要的(我不是100%确定我理解你的问题以及你想要完成的事情)但是:
如何同时提供:joins
和:includes
?
Person.find(
:all,
:joins => 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_',
:includes => :companies
)
或AR3方式:
Person.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')
答案 3 :(得分:1)