2014-08-30 66 views
1

我正在尝试重新设计我的Laravel 4.2代码,并希望在最后几天将结果分组。Laravel groupBy

代码:

public function getTrending($type = null, $category = null) 
{ 
    $posts = $this->posts($type, $category)->with('comments', 'votes', 'category', 'user', 'votes.user') 
     ->leftJoin('votes', 'posts.id', '=', 'votes.post_id') 
     ->leftJoin('comments', 'posts.id', '=', 'comments.post_id') 
     ->select('posts.*', DB::raw('count(comments.post_id)*7 + count(votes.post_id)*30 + posts.views as popular')) 
     ->groupBy('posts.id')->with('user')->orderBy('popular', 'desc')->whereMonth('posts.created_at', '>=', date('n', strtotime('-1 month'))) 
     ->paginate(perPage()); 

    return $posts; 
} 

我想组的结果,因为它是(相关:评论,投票,访问)+分组上每天基地的结果。

喜欢:

今天(与日期xx.xx.xx)

  • 结果1(最多投票,评论,...)
  • 结果2
  • 结果3

昨天(日期xx.xx.xx)

  • 结果4(最多投票,评论,...)
  • 结果5
  • 结果6

这可能吗?

+0

使用碳,请参阅下面的答案。 – 2014-12-18 09:15:10

回答

-1

不,我不相信你可以将数据分组在一个单一的查询中。

假设你的代码是给你你想要的数据集,而不按日期分组,我会遍历我想日期,并获取数据,每天与日期格式化标题等

+0

这并不是试图回答这个问题,而应该是一个评论。 – EWit 2014-08-30 09:45:22

0

你可以使用碳;

->groupBy(function($date) { 
     return Carbon::parse($date->created_at)->format('Y'); // grouping by years 
     //return Carbon::parse($date->created_at)->format('m'); // grouping by months 
    });