Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 262
Oviron Avatar asked Oct 18 '22 00:10

Oviron


1 Answers

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.

like image 94
Andrey Skuratovsky Avatar answered Oct 29 '22 17:10

Andrey Skuratovsky