【问题标题】:Laravel - group posts by months (eager loading)Laravel - 按月分组帖子(渴望加载)
【发布时间】:2014-07-09 04:46:24
【问题描述】:

我想按月份列出我的帖子

这是我的类别模型

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 个帖子,但我想以某种方式将同一个月内的帖子分组,以便我可以在按月分组的视图中列出它们

我尝试在我的 Category 模型中将 groupBy('month') 添加到我的帖子方法(关系)中,但这只会让事情变得更糟,因为这样我每个月只能收到一篇帖子

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

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

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

谁能指点我正确的方向,非常感谢。

【问题讨论】:

    标签: php laravel group-by eager-loading


    【解决方案1】:

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

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

    【讨论】:

    • 那不行,它只是不断加载和加载,没有任何反应
    • 只有 5 个,但我用不同的方式解决了它,我明天会发布答案,今晚很累。无论如何谢谢@Josep
    • @Mr.Sam 你不想发布答案吗?
    • @Mr.Sam 你不想发布答案吗?
    • @Mr.Sam 您不想发布答案吗?
    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    相关资源
    最近更新 更多