Home > OS >  how to convert below SQL query in Laravel query?
how to convert below SQL query in Laravel query?

Time:07-13

how to convert below sql query in laravel

 SELECT `models`.* FROM (
        (SELECT * FROM `models` WHERE `models`.`fk_car_model_id` = 3 LIMIT 5) 
        UNION ALL 
        (SELECT * FROM `models` WHERE `models`.`fk_car_model_id` = 2 LIMIT 3) 
        UNION ALL 
        (SELECT * FROM `models` WHERE `models`.`fk_car_model_id` = 1 LIMIT 2) 
    ) AS `models`

CodePudding user response:

// if you want to get all the fields, you can use the following:
$fields = '*';
// if you want to select only some fields, use this:
// $fields = [
//     'id',
//     'fk_car_model_id',
// ];

$data = Model::select($fields)
    ->where('fk_car_model_id', 3)->limit(5)
    ->unionAll(
        Model::select($fields)
            ->where('fk_car_model_id', 2)->limit(3)
    )
    ->unionAll(
        Model::select($fields)
            ->where('fk_car_model_id', 1)->limit(2)
    )
    ->get()
    ->toArray();

return $data;

Or you can use something like this:

$query = DB::table('models')
    ->select('models.*')
    ->where('models.fk_car_model_id', '=', 3)
    ->limit(5)
    ->unionAll(
        DB::table('models')
            ->select('models.*')
            ->where('models.fk_car_model_id', '=', 2)
            ->limit(3)
    )
    ->unionAll(
        DB::table('models')
            ->select('models.*')
            ->where('models.fk_car_model_id', '=', 1)
            ->limit(2)
    )
    ->get();

CodePudding user response:

Please check it, this might help you. This might not b exact as you want but you can get some idea about its working and change as per you requirements.

    Model::where(function ($query) {
    $query->where('fk_car_model_id', '=', 3)
                ->limit(5)
     })->orWhere(function ($query) {
    $query->where('fk_car_model_id', '=', 2)
                ->limit(3)
     })->orWhere(function ($query) {
     $query->where('fk_car_model_id', '=', 1)
                ->limit(2)
     })->get();

See more for Documentation for reference Logical Grouping

  • Related