Tuesday, March 14, 2017

PHP& MySQL - Query multiple times on same columns, with different values, but with AND condition

I have a table with following structure:

id, metable_id, meta_key, meta_value

*Looks like posts_meta from WordPress, in case you found it familiar. In my query, I need to retrieve metable_id where

meta_key = 'departure_location'
AND
meta_value = 'New York'
BUT AND
meta_key = 'arrival_location'
meta_value = 'Los Angeles'

In other words, I need to retrieve metable_id of posts that depart from New York AND arrive in Los Angeles

OR condition is not suitable, as it will return posts that depart from New York and arrive anywhere, and posts that arrive to Los Angeles but depart from anywhare. How shold this query look like ? I'm building my app using Laravel, so a Laravel Query-Builder response would be even more appreciated. I need some kind of query composer, to be able to pass any meta_key and values, and query should parse them all with AND condition (this will be used for futher filtering, by price, and any other meta_keys). Could you please help me build the query ?



via Nicolae Cojocaru

Advertisement