Nested orwhere in one where - Laravel

Viewed 286

I need to build a query in Laravel 6 that has nested where's in one where query. for example: Select * FROM example where k=5 and ((i=1 and j=2) or (i=3 and j=4) or (i=5 and j=4)......)

i tried the code below

                $getItems = $getItems->where(function ($query) use($codes,$cID) {
                        $query->orWhere(function ($query1) use ($codes, $cID) {
                            foreach($codes[$cID] as $code) {
                                $query1
                                    ->where('code', $code)
                                    ->where('cid', $cID);
                            }
                        });
                });

but the result is wrong.

and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?)) and (("code" = ? and "cid" = ?))....

I don't understand why it adds 2 parenthesis in every foreach loop and why it adds "and" instead of "or". Any suggestions on how to build this?

1 Answers

You should have structure like this:

Model::where('k', 5)->where(function($q){
        $q->orWhere(function($q){
            $q->where('i', 1)->where('j', 2);
        })->orWhere(function($q){
            $q->where('i', 3)->where('j', 4);
        })->orWhere(function($q){
            $q->where('i', 5)->where('j', 4);
        });
    })->toSql();

> select * from `table` where `k` = ? and ((`i` = ? and `j` = ?) or (`i` = ? and `j` = ?) or (`i` = ? and `j` = ?))

So your query should be:

$getItems->where('k', 5)
    ->where(function ($query) use($codes, $cID) {
        foreach($codes[$cID] as $code) {
            $query->orWhere(function ($query1) use ($code, $cID) {
                $query1->where('code', $code)->where('cid', $cID);
            });
        }
    });
Related