Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple groupBy on Laravel Collection

I am trying to group a collection by two clauses in Laravel 5, but it only groups it by the first one. Can someone please help me out? Here's my code.

$query = Activity::all()->groupBy('performed_at_year_month', 'performer_id')->toJson();
like image 294
Michalis Antoniou Avatar asked May 26 '15 21:05

Michalis Antoniou


1 Answers

The solution in https://stackoverflow.com/a/30469061/221745 can be improved on I think. The key is to remember that a grouped by collection is a collection of collections. Therefore, the following will work:

<?php

$recs = new \Illuminate\Database\Eloquent\Collection($query);
$grouped = $recs->groupBy('performed_at_year_month')->transform(function($item, $k) {
    return $item->groupBy('performer_id');
});

Where $grouped contains your final result

like image 129
Erik Avatar answered Oct 15 '22 19:10

Erik