Combining multiple results when joining tables: a step-by-step guide
P粉769045426
P粉769045426 2024-04-04 09:44:27
0
1
575

I have a query that returns the names of categories and their subcategories.

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

Now the results I get are as follows:

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

How can I group it like this:

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

Is it possible without too many loop iterations and check which subcategory belongs to which category?

P粉769045426
P粉769045426

reply all(1)
P粉513318114

You can use laravelCollections

First you need to group by the groupBy method, then map each group and merge each sub-array.

$result = collect($subcategories)
        ->groupBy('catname')
        ->map(function ($item) {
            return array_merge($item->toArray());
        })->all();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template