Home > Blockchain >  Laravel Eloquent WhereNot multidemensional array
Laravel Eloquent WhereNot multidemensional array

Time:01-06

I'm trying to retrieve all rows where the conditions do not apply. The SQL query looks a bit like this:

SELECT * FROM range
WHERE NOT (
    (from = 1000 AND to = 2000) OR (from = 2000 AND to = 3000)
);

In my code I do something like this:

$array = [
    [
        'from' => 1000,
        'to' => 2000,
    ],
    [
        'from' => 2000,
        'to' => 3000
    ]
];

$this->whereNot(function ($query) use ($array) {
    foreach($array as $item) {
        $query->where($item);
    }
});

The query will sadly looks like this:

SELECT * FROM range
WHERE NOT (
    (from = 1000 AND to = 2000) AND (from = 2000 AND to = 3000)
);

I've been trying multiple things but I can't figure out an elegant way to achieve this. I've fixed it for now like this:

$this->whereNot(function ($query) use ($array) {
    foreach($array as $i => $item) {
        if($i == 0) {
            $query->where($item);
        } else {
            $query->orWhere($item);
        }
    }
});

It works, but I'm very curious if someone found a way to do this without checking the iterator count.

CodePudding user response:

use orWhere

->whereNot(function ( $query)use( $array){

        foreach ( $array  as $value){
            $query->orWhere(function ($q)use($value){
                $q->where('from', $value['from'])->where("to",$value['to']);
            });
        }
       
    })

or

->whereNot(function ( $query)use( $array){

        foreach ( $array  as $value){
            $query->orWhere(function ($q)use($value){
                $q->where($value);
            });
        }
    })
  • Related