Framework: orWhere: bug or feature?

Created on 5 Jul 2018  路  4Comments  路  Source: laravel/framework

  • Laravel Version: v5.6.26
  • PHP Version: 7.2.7
  • Database Driver & Version: MySQL 5.5

I do select value in the database, use two param group:

Catalogs::where(['column_one' => $val_xx, 'column_two' => $val_yy])->orWhere(['column_one' => $val_zx, 'column_two' => $val_zy])

and i get

select * where (column_one= '$val_xx' andcolumn_two= '$val_yy') or (column_one= '$val_zx' orcolumn_two= '$val_zy')

Why operator OR within second group? When i used laravel 5.2, within second group was operator AND.

Most helpful comment

Imo the easiest way around is:

Catalogs::where(function ($query) use ($val_xx, $val_yy) {
    $query->where('column_one', $val_xx);
    $query->where('column_two', $val_yy);
})->orWhere(function ($query) use ($val_zx, $val_zy) {
    $query->where('column_one', $val_zx);
    $query->where('column_two', $val_zy);
});

I think it looks better, you can clearly see the groups.

All 4 comments

I would see it as a bug: #20553

But if we fix it, it breaks the code of people who are expecting the current behavior.

Imo the easiest way around is:

Catalogs::where(function ($query) use ($val_xx, $val_yy) {
    $query->where('column_one', $val_xx);
    $query->where('column_two', $val_yy);
})->orWhere(function ($query) use ($val_zx, $val_zy) {
    $query->where('column_one', $val_zx);
    $query->where('column_two', $val_zy);
});

I think it looks better, you can clearly see the groups.

Use with Model:

Catalogs::where(["column_one" => $column_one, "column_two" => $column_two])
         ->whereRaw("(column_one=? or column_two=?)", [$column_one, $column_two]);

Generate sql:

 select .... from cataglogs where column_one=? and column_two=? and (column_one=? or column_two=?)

Please use @wik-z suggestion

Was this page helpful?
0 / 5 - 0 ratings