Home > Mobile >  Laravel eloquent query group where clause returns wrong query
Laravel eloquent query group where clause returns wrong query

Time:02-08

I have a MySQL query:

select * from `contents`
 where `vei_sn` = '22566' 
    and `op_date` >= '2022-02-07' 
    and `op_date` <= '2022-02-07'
     and not (`ecu` = 'ACM' and `ecu_sub` = 2.1 and `parameters` = 'TorqueLimit2') 
order by `op_full_date` desc limit 31 offset 0

and I want to transform it into eloquent. I wrote this eloquent query, but it output the wrong query results:

OplogContent::query()
            ->where('vei_sn', $device->serial_number)
            ->where('op_date', '>=', $request->date_from)
            ->where('op_date', '<=', $request->date_to)
            ->where(function ($q) {
                $q->where('ecu', '!=', 'ACM')
                  ->where('ecu_sub', '!=', 2.1)
                  ->where('parameters', '!=', 'TorqueLimit2');
            });
            ->orderBy('op_full_date', 'desc')
            ->simplePaginate(30)

//// but it returns this MySQL query //////
select * from `contents` 
 where `vei_sn` = '22566' 
  and `op_date` >= '2022-02-07' 
   and `op_date` <= '2022-02-07' 
    and (`ecu` != 'ACM' and `ecu_sub` != 2.1 and `parameters` != 'TorqueLimit2') 
order by `op_full_date` desc limit 31 offset 0

How to change my eloquent query, that MySQL where grouping clause will be and not (`ecu` = 'ACM' and `ecu_sub` = 2.1 and `parameters` = 'TorqueLimit2') ?

CodePudding user response:

The problem is about the boolean algebra. If you use NOT(a & b) it is equal to NOT a | NOT b.

So this line translated to query:

and not ('ecu' = 'ACM' and 'ecu_sub' = 2.1 and 'parameters' = 'TorqueLimit2')

 ->where(function ($q) {
            $q->where('ecu', '!=', 'ACM')
              ->orWhere('ecu_sub', '!=', 2.1)
              ->orWhere('parameters', '!=', 'TorqueLimit2');
        });
  •  Tags:  
  • Related