Laravel Collection上有多个groupBy

Mic*_*iou 15 php group-by laravel eloquent

我试图通过Laravel 5中的两个子句对一个集合进行分组,但它只将它分组到第一个.有人可以帮帮我吗?这是我的代码.

$query = Activity::all()->groupBy('performed_at_year_month', 'performer_id')->toJson();
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 32

我认为可以改进/sf/answers/2132834301/中的解决方案.关键是要记住按集合分组是集合的集合.因此,以下将起作用:

<?php

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

哪里$grouped包含您的最终结果


bri*_*itt 11

Laravel 现在(自 5.5.29 起)支持多级嵌套分组,根据https://christoph-rumpel.com/2018/1/groupby-multiple-levels-in-laravel

$query = Activity::all()->groupBy(['performed_at_year_month', 'performer_id'])->toJson();
Run Code Online (Sandbox Code Playgroud)


use*_*496 6

您可以尝试将它们链接起来,但我不确定它会为您提供所需的结果.可能想检查一下

$query = Activity::all()->groupBy('performed_at_year_month')->groupBy('performer_id')->toJson();
Run Code Online (Sandbox Code Playgroud)

我刚刚检查了这一点你是对的,它不是保留键,虽然我想我可以猜到为什么.如果一个密钥碰巧是相同的,那么事情就会被覆盖.也许很难确定哪个键是什么,总体感觉有点"hacky"可能有更好的解决方案.

但是,我想我已经想出了如何做到这一点.

$query = Activity::all();
$activities = new \Illuminate\Database\Eloquent\Collection($query);
$activities = $activities->groupBy('performed_at_year_month')->toArray() + $activities->groupBy('performer_id')->toArray();
echo json_encode($activities);
Run Code Online (Sandbox Code Playgroud)


Bed*_*ang 5

您可以传递回调而不是传递字符串键。回调应返回您希望通过以下方式键入组的值:

$collection->groupBy(function($item, $key){
            return $item["key-1"]."-".$item["key-2"];
        });
Run Code Online (Sandbox Code Playgroud)

参考:- https://laravel.com/docs/5.7/collections#method-groupby