Search code examples
laravellaravel-query-builder

Laravel QueryBuilder multiple columns match in the same WhereIn


I would have liked to convert a SQL query like this one in Laravel Eloquent. This query works on MariaDb but i don't know about other engines (might be the reason why it isn't implented):

id year country enabled
0 2000 "France" 0
1 2001 "Spain" 0
2 2002 "France" 1
3 2003 "Germany" 1

SELECT id FROM my_db.countries WHERE (name, enabled) IN (("France", 1), ("Spain", 0));

This returns 1 and 2.

This is possible with Eloquent (as suggested here: laravel whereIn multiple columns but it wouldn't return the expected results:

DB::table('countries')->select('id')->whereIn('name', ["france", "Spain"])->whereIn('enabled', [0, 1])->all();

This returns 0, 1 and 2.

I gave a shot at adapting the Illuminate/Database library to fit my needs but the databinding started to get really complexe.

I managed to make it with a whereRaw query but it isn't really clean enough for production code as there are no data binding (values shows up with ->toSql()).

Does anyone have an idea?


Solution

  • The query syntax you want to get:

    SELECT id FROM my_db.countries WHERE (name, enabled) IN (("France", 1), ("Spain", 0));
    

    is exclusive to Oracle. The whereIn method of Laravel supports (String, Array), so I think you only have the options to do it through raw queries or using the solution proposed by V-K