两个关系的交集

编程入门 行业动态 更新时间:2024-10-10 23:21:14
本文介绍了两个关系的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

说我有两个关系持有记录在同一个模型,如:

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.

更多推荐

两个关系的交集

本文发布于:2023-07-14 10:32:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1104116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   关系

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!