[英]Complex Sql Query to RoR ORM
我有一个非常复杂的SQL查询,我想将其转换为RoR的ORM。
SELECT c.* FROM (SELECT companies.* FROM companies WHERE city = "?" AND country = "?") AS c INNER JOIN tagsForCompany AS tc ON c.id = tc.Company INNER JOIN tags AS t ON t.id = tc.TID WHERE t.Name REGEXP '?'
我已经定义了这样的模型:
companies.rb
class Company < ActiveRecord::Base
# ... Some code that doesn't matter
has_and_belongs_to_many :tags
# ... Some other code
end
和tags.rb
class Tag < ActiveRecord::Base
has_and_belongs_to_many :company
end
我需要公司控制器中的一个函数来搜索像上面的查询这样的公司。
选项:
首先 : find_by_sql()
说明:允许您在其上放置任何查询。
http://apidock.com/rails/ActiveRecord/Base/find_by_sql/class
第二 :组合.where()
和.joins()
方法。
但要小心,如果你调用.joins()
一后.where()
与零回报,你会得到未定义方法的错误。 解决方案是首先测试.where()
返回任何内容,然后可以与另一个表连接。
使用联接的可能方法:
joins(:tags)
创建一个内部联接
joins('Left join foo...')
使您可以使用左外连接
joins(tagsForCompanies: :tags)
如果您有N到N个关联,则为嵌套联接。
查看API:
http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where
http://guides.rubyonrails.org/active_record_querying.html#joining-tables
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.