2015-07-20 79 views
2

我正在尝试创建一个Eloquent查询,获取每个不同日期发布的帖子总数,如果缺少日期,请使用值填充零。从每个不同的日期计数,填写缺失的日期为零

例如,如果我的表看起来像这样:

+----+---------------------+ 
| id |  date   | 
+----+---------------------+ 
| 1 | 2015-01-01 00:00:00 | 
| 2 | 2015-01-01 01:53:18 | 
| 3 | 2015-01-01 02:41:26 | 
| 4 | 2015-01-02 12:51:01 | 
| 5 | 2015-01-05 08:24:12 | 
+----+---------------------+ 

这将输出:

2015-01-01 : 3 
2015-01-02 : 1 
2015-01-05 : 1 

但请注意,这天03-04失踪。我怎么能包括这些日期,但给他们0,使得我最终的输出,如值:

2015-01-01 : 3 
2015-01-02 : 1 
2015-01-03 : 0 
2015-01-04 : 0 
2015-01-05 : 1 

这里是我当前的查询:

$posts = Post::select(array(
     DB::raw('DATE(`created_at`) as `date`'), 
     DB::raw('COUNT(*)as `count`') 
    )) 
    ->where('created_at', '>', Carbon::today()->subWeek()) 
    ->groupBy('date') 
    ->orderBy('date', 'DESC') 
    ->lists('count', 'date'); 

谢谢!

+0

还能有关于日期的范围内的任何假设?例如,您事先知道日期将介于2015-01-01至2015-01-31之间? – CrackingTheCode

+0

@CrackingTheCode日期总是从7天前一直到今天。 – asd651asd

回答

2

在你的SQL结果中,你可以在你的行中生成一些“假数据”,但是你不能生成“假行”,不会加入到某个“假(临时)表”中。 在你的情况下,在sql-result上应用一些逻辑要容易得多。

这种替换代码:

$order    = 'DESC'; 
$endDate   = Carbon::today(); 
$startDate   = Carbon::today()->subWeek(); 

$dateInc   = ($order == 'DESC') ? -1 : 1; 
$dateCycleHolder = clone ($dateInc > 0 ? $startDate : $endDate); 
$dateCycleEnd  = clone ($dateInc > 0 ? $endDate : $startDate); 


$posts = Post::select(array(
    DB::raw('DATE(`created_at`) as `date`'), 
    DB::raw('COUNT(*)as `count`') 
)) 
    ->where('created_at', '>', $startDate) 
    ->groupBy('date') 
    ->orderBy('date', $order) 
    ->lists('count', 'date'); 

$postsFinal = new \Illuminate\Database\Eloquent\Collection(); 

while ($dateCycleHolder->ne($dateCycleEnd)) { 
    $dateCurr = $dateCycleHolder->format('Y-m-d'); 
    $postsFinal->put($dateCurr, $posts->get($dateCurr, 0)); 
    $dateCycleHolder->addDay($dateInc); 
} 
$dateCurr = $dateCycleHolder->format('Y-m-d');  
$postsFinal->put($dateCurr, $posts->get($dateCurr, 0)); 

$posts = $postsFinal; 

其小有一点位灵活,你可以改变的这样的事情值:

$order    = 'DESC'; 
$endDate   = Carbon::today(); 
$startDate   = Carbon::today()->subWeek();