【发布时间】: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