简体   繁体   English

使用通配符对阵列列进行Activerecord查询

[英]Activerecord query against array column using wildcard

So let's say i have a Customer model with array column phones . 所以,假设我有一个带阵列列phonesCustomer模型。 It's pretty easy to find all customers with given phone 通过手机找到所有客户非常容易

Customer.where('? = ANY(phones)', '+79851234567')

But i can't figure out how to use LIKE with wildcard when i want to find customers with phones similar to given one, something like: 但是,当我想找到类似于给定的手机的客户时,我无法弄清楚如何使用LIKE和通配符,例如:

Customer.where('ANY(phones) LIKE ?', '+7985%')

I'm using PostgreSQL 9.5 and Rais 4.2 我正在使用PostgreSQL 9.5和Rais 4.2

Any ideas? 有任何想法吗?

I think, first of all, its better to use second table phones with fields customer_id, phone_number. 我认为,首先,最好使用带有customer_id,phone_number字段的第二台手机。 I think it's more rails way ). 我认为这是更多的轨道方式)。 In this way you can use this query 通过这种方式,您可以使用此查询

Phone.where("phone_number LIKE ?", '%PART%').first.customer

If you serialize your array in some text field, by example JSON, you should use % on both sides of your pattern: 如果您在某些文本字段中序列化数组(例如JSON),则应在模式的两端使用%:

Customer.where('phones LIKE ?', '%+7985%')

If you have an array in your database, you should use unnest() function to expand an array to a set of rows. 如果数据库中有数组,则应使用unnest()函数将数组扩展为一组行。

Can you try this 你能试试吗?

Customer.where("array_to_string(phones, ', ') like ?", '+7985%')

I believe this will work. 我相信这会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM