Skip to content
Advertisement

Convert Raw SQL ‘NOT’ IN (too slow) to Laravel Eloquent

I have a running script using Raw SQL in Laravel 5.3 controller which I found it slow and not secure ( as Raw ). If there any way to make it more effecient and convert it to eloquent or Query Builder for Laravel ?

code as below & Thanks !

SELECT  machine_code, machine_name
FROM    factory_equipment
WHERE  machine_code  NOT IN
    (
        SELECT  distinct(machine_code)
        FROM    echecklist_data
        WHERE   DATE_FORMAT(date, '%Y-%m-%d') = CURDATE() 
    )
  AND type='production' ORDER BY machine_code ASC

Advertisement

Answer

I managed to get it working using laravel’s query. Hope it helps others

DB::table('factory_equipment')
        ->select('factory_equipment.machine_code', 'factory_equipment.machine_name')
        ->leftjoin('echecklist_data', function ($leftjoin) {
            $leftjoin->on('factory_equipment.machine_code', '=', 'echecklist_data.machine_code')
            ->Where( DB::raw("DATE_FORMAT(echecklist_data.date, '%Y-%m-%d')"), DB::raw("CURDATE()") );
            })
        ->where('factory_equipment.type' , '=', 'production') 
        ->whereNull('echecklist_data.machine_code')         
        ->get();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement