简体   繁体   中英

Activerecord query against array column using wildcard

So let's say i have a Customer model with array column phones . 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:

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

I'm using PostgreSQL 9.5 and Rais 4.2

Any ideas?

I think, first of all, its better to use second table phones with fields 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:

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.

Can you try this

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

I believe this will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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