Ruby-on-rails ActiveRecord 中的多个或条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10289522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple or conditions in ActiveRecord
提问by Rafael Almeida
I have two tables: Lawyer and Phone. Phone is separated into area code and number. A lawyer has many phones. I want to produce a query which searches for lawyers who have a phone matching a phone from a list of phones.
我有两张表:Lawyer 和 Phone。电话分为区号和号码。律师有很多电话。我想生成一个查询,该查询从电话列表中搜索拥有与电话匹配的电话的律师。
If I had only one phone I could search it like this:
如果我只有一部手机,我可以这样搜索:
Lawyer.join(:phones).where(:area_code => area_code, :number => number)
The problem is that I have a list with more than one area code. So I really want to do something like this:
问题是我有一个包含多个区号的列表。所以我真的很想做这样的事情:
lawyers = []
phones.each { |phone| lawyers += Lawyer.join(:phones).where(:area_code => phone[:area_code], :number => phone[:number]) }
However, I don't want to make many queries. Can't it be done in a single query statement?
但是,我不想做很多查询。不能在单个查询语句中完成吗?
Edit: This is how I would do a similar thing using SQL alone (assuming the list of numbers was [{:area_code=>'555', :number=>'1234564'}, {:area_code=>'533', :number=>'12345678'}])
编辑:这就是我单独使用 SQL 做类似事情的方式(假设数字列表是 [{:area_code=>'555', :number=>'1234564'}, {:area_code=>'533', : number=>'12345678'}])
select * from phones where (area_code, number) in (('555', '1234564'), ('533', '12345678'))
If someone can get that translated into ActiveRecord, that'd be great.
如果有人能把它翻译成 ActiveRecord,那就太好了。
回答by miked
If you pass an array of area_codes, AR will build an IN condition. So you could use your original search and use arrays instead:
如果您传递一个 area_codes 数组,AR 将构建一个 IN 条件。因此,您可以使用原始搜索并改用数组:
where area_codes is an array of area_codes and numbers an array of numbers:
其中 area_codes 是一个 area_codes 数组, numbers 是一个数字数组:
Lawyer.join(:phones).where(:area_code => area_codes, :number => numbers)
or:
或者:
Lawyer.join(:phones).where("phones.area_code IN (?) AND phones.number IN (?)", area_codes, numbers)
Should yield:
应该产生:
SELECT * from lawyers JOIN phones ON phones.lawyer_id = lawyers.id WHERE phones.area_code IN (...) AND phones.number IN (...)
回答by xjlin0
Lawyer.join(:phones).where(
"(phones.area_code, phones.number) IN ( ('555', '5555555'), ('444', '12345678') )"
)

