Home > Enterprise >  How to combine multiple results while joining tables
How to combine multiple results while joining tables

Time:04-19

I have a query which returns names of categories and its subcategories.

$subcategories = Subcategory::select('subcategories.name as subcatname', 'categories.name as catname')
                ->join('categories', 'subcategories.idCategory', '=', 'categories.id')
                ->get();

And now I get results like:

'Music' => 'Jazz',
'Music' => 'Rock',
'Music' => 'Pop',
'Movie' => 'Action'

How can I group it to have something like this:

'Music' => array('Jazz', 'Rock','Pop'),
'Movies' => array('Action')

Is it possible without making to much looping iterations and checking which subcategory belongs to which category?

CodePudding user response:

You can use laravel collection

First you need to group by groupBy method, then map each group and merge every child array.

$result = collect($subcategories)
        ->groupBy('catname')
        ->map(function ($item) {
            return array_merge($item->toArray());
        })->all();
  • Related