harunB10
harunB10

Reputation: 5197

How to combine multiple results while joining tables

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?

Upvotes: 0

Views: 38

Answers (1)

Faizul Islam
Faizul Islam

Reputation: 77

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();

Upvotes: 1

Related Questions