Laravel - 按月分组(急切加载)

时间:2014-07-08 20:23:35

标签: php laravel group-by eager-loading

我想列出按月分组的帖子

这是我的分类模型

class Category extends \Eloquent {
    public function posts()
    {
        return $this->belongsToMany('Post', 'category_post_tag')
                    ->select(DB::raw('MONTH(posts.eventStartDate) month, MONTHNAME(posts.created_at) month_name'))
                    ->distinct()
                    ->orderBy('eventStartDate', 'asc');
    }
}

所以当我在我的视图文件中执行此操作时:

@foreach($category->posts as $index => $post)
    <pre>{{ $post }}</pre>
@endforeach

我得到了这个结果:

{"month":"7","month_name":"July","id":"20","slug":"sunt-et-ipsum-dolorum","title":"Sint dolorum exercitationem."}
{"month":"7","month_name":"July","id":"15","slug":"qui-exercitationem-autem","title":"Id tenetur rem cumque ut."}
{"month":"8","month_name":"July","id":"6","slug":"aspernatur-qui-repellat","title":"Recusandae accusamus omnis dicta."}
{"month":"9","month_name":"July","id":"25","slug":"et-aut-eos-quaerat-soluta-perspiciatis","title":"Facere ullam sint et."}
{"month":"10","month_name":"July","id":"26","slug":"sunt-nemo-aperiam","title":"Voluptatibus harum sunt et ducimus."}

哪个好,因为我只有5个帖子,但我想以某种方式对同一个月的帖子进行分组,以便我可以在我的视图中将它们列出按月分组

我尝试在我的分类模型中将groupBy(&#39; month&#39;)添加到我的帖子方法(关系),但这只会让事情变得更糟,因为那时我只回复一个帖子/月

所以我在我的视图文件中尝试了这个:

@foreach($category->posts as $index => $post)
    {{ $new_array[$post->month][$post->id] = $post }}
@endforeach

创建一个按月分组的新数组,但这会冻结我的浏览器,它只是继续加载,最后死机时会出现白屏。

有人可以指出我正确的方向,非常感谢你。

1 个答案:

答案 0 :(得分:1)

对集合使用groupBy,而不是查询:

$category->posts->groupBy('month');