ruby-on-rails – 两个关系的交集
发布时间:2020-12-16 21:45:50 所属栏目:百科 来源:网络整理
导读:说我有两个关系在同一个模型中保存记录,如: @companies1 = Company.where(...)@companies2 = Company.where(...) 我如何找到这两个关系的交集,即只有那些存在于两者之间的公司? 解决方法 默认情况下连接那些在一起创建的,哪个是你想要的. 这么多是: class
说我有两个关系在同一个模型中保存记录,如:
@companies1 = Company.where(...) @companies2 = Company.where(...) 我如何找到这两个关系的交集,即只有那些存在于两者之间的公司? 解决方法
默认情况下连接那些在一起创建的,哪个是你想要的.
这么多是: class Company < ActiveRecord::Base def self.where_1 where(...) end def self.where_2 where(...) end end @companies = Company.where_1.where_2 ====== UPDATED ====== 有两种情况: # case 1: the fields selecting are different Company.where(:id => [1,2,3,4]) & Company.where(:other_field => true) # a-rel supports &,|,+,-,but please notice case 2 # case 2 Company.where(:id => [1,3]) & Company.where(:id => [1,4,5]) # the result would be the same as Company.where(:id => [1,5]) # because it is &-ing the :id key,instead of the content inside :id key 所以如果你是2,你需要像@apneadiving这样评论. Company.where(...).all & Company.where(...).all 当然,这样做会发出两个查询,最有可能查询比您需要的更多的结果. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |