Home  >  Q&A  >  body text

Combining multiple results when joining tables: a step-by-step guide

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粉769045426P粉769045426171 days ago316

reply all(1)I'll reply

  • P粉513318114

    P粉5133181142024-04-05 00:21:42

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

    reply
    0
  • Cancelreply