Laravel query - Join and GroupBy

Viewed 5200

I'm using laravel and I'm trying to select some stuff from the table..

$cars= DB::table('cars')
        ->leftJoin('types', 'cars.type_id', '=', 'types.id')
        ->groupBy('types.id')->get();

Basically I want 'cars' grouped in subarrays of the same "types".. but it ends up merging all group entries into only one of each car.

How can I make this query?

1 Answers

If it happens that type is what you want and is merged in the return set of the $car, you may even remove groupBy like so

  $cars= DB::table('cars')
          ->leftJoin('types', 'cars.type_id', '=', 'types.id')
          ->get();

and then group result set with groupBy() like so

   $cars->groupBy('type');

Remember this is possible since the result set is some sort of collection. Thus the final code will look like this

   $cars= DB::table('cars')
      ->leftJoin('types', 'cars.type_id', '=', 'types.id')
      ->get();

    return $cars->groupBy('type');
Related