本文介绍了两个关系的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有两个关系持有记录在同一个模型,如:
Say I have two relations that hold records in the same model, such as:
@companies1 = Company.where(...) @companies2 = Company.where(...)我
如何才能找到这两个关系的交集,即只有在同时存在,这些公司?
How can I find the intersection of these two relations, i.e. only those companies that exist within both?
推荐答案在默认情况下连接这些其中,一起创建并这是你想要的。
By default connecting those where together creates AND which is what you want.
因此,许多是:
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, 2, 3]) & Company.where(:id => [1, 2, 4, 5]) # the result would be the same as Company.where(:id => [1, 2, 4, 5]) # because it is &-ing the :id key, instead of the content inside :id key
所以,如果你是在第二种情况下,你需要做的像什么@apneadiving评论。
So if you are in case 2, you will need to do like what @apneadiving commented.
Company.where(...).all & Company.where(...).all
当然,这样做发出两个查询,并最有可能的查询比你需要更多的结果。
Of course, doing this sends out two queries and most likely queried more results than you needed.
更多推荐
两个关系的交集
发布评论