当前位置:  开发笔记 > 编程语言 > 正文

如何通过rails中的自定义连接来加载对象?

如何解决《如何通过rails中的自定义连接来加载对象?》经验,为你挑选了1个好方法。

你能不能使用ActiveRecord添加连接条件?

例如,我有一个非常复杂的查询使用几个依赖记录,它通过组合条件和包含指令工作正常

Contractors.find(
  :all, 
  :include => {:council_areas => :suburbs},
  :conditions => ["suburbs.postcode = ?", customer.postcode]                 
)    

假如说:

    承包商有很多议员

    CouncilAreas拥有很多郊区

此连接返回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> Toby Hede..:

你能不能使用ActiveRecord添加连接条件?

例如,我有一个非常复杂的查询使用几个依赖记录,它通过组合条件和包含指令工作正常

Contractors.find(
  :all, 
  :include => {:council_areas => :suburbs},
  :conditions => ["suburbs.postcode = ?", customer.postcode]                 
)    

假如说:

    承包商有很多议员

    CouncilAreas拥有很多郊区

此连接返回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')

(注意:为简洁起见,我编辑了列列表).

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有