gpt4 book ai didi

ruby-on-rails - ActiveRecord中的倍数或条件

转载 作者:行者123 更新时间:2023-12-03 22:21:35 25 4
gpt4 key购买 nike

我有两个表:律师和电话。电话分为区号和号码。律师有很多电话。我想产生一个查询,该查询从电话列表中搜索具有与电话匹配的电话的律师。

如果我只有一部手机,可以这样搜索:

Lawyer.join(:phones).where(:area_code => area_code, :number => number)


问题是我有一个包含多个区号的列表。所以我真的想做这样的事情:

lawyers = []
phones.each { |phone| lawyers += Lawyer.join(:phones).where(:area_code => phone[:area_code], :number => phone[:number]) }


但是,我不想进行很多查询。不能在单个查询语句中完成吗?

编辑:这就是我将单独使用SQL进行类似操作的方式(假设数字列表为[{:area_code =>'555',:number =>'1234564'},{:area_code =>'533',: number =>'12345678'}])

select * from phones where (area_code, number) in (('555', '1234564'), ('533', '12345678'))


如果有人可以将其转换为ActiveRecord,那就太好了。

最佳答案

如果您传递一个area_codes数组,AR将建立一个IN条件。因此,您可以使用原始搜索并改为使用数组:

其中area_codes是area_codes的数组,数字是数字的数组:

 Lawyer.join(:phones).where(:area_code => area_codes, :number => numbers)


要么:

 Lawyer.join(:phones).where("phones.area_code IN (?) AND phones.number IN (?)", area_codes, numbers)


应该产生:

 SELECT * from lawyers JOIN phones ON phones.lawyer_id = lawyers.id WHERE phones.area_code IN (...) AND phones.number IN (...)

关于ruby-on-rails - ActiveRecord中的倍数或条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10289522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com