首页 文章

Laravel Collection上有多个groupBy

提问于
浏览
13

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

$query = Activity::all()->groupBy('performed_at_year_month', 'performer_id')->toJson();

2 回答

  • 27

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

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

    $grouped 包含您的最终结果

  • 6

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

    $query = Activity::all()->groupBy('performed_at_year_month')->groupBy('performer_id')->toJson();
    

    我刚刚检查了这个,你说的是正确的,它不是保留钥匙,虽然我想我可以猜到为什么 . 如果一个密钥碰巧是相同的,那么事情就会被覆盖 . 也许很难确定哪个键是什么,总体感觉有点“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);
    

相关问题