2016-10-04 80 views
0

我想查询我的模型,并返回一个对象喂到chart.js之从模型中获取过去7天的数据?

// Configure dates 
$today = Carbon::today(); 
Carbon::setTestNow($today->subWeek()); 
$sunday = new Carbon('this sunday'); 
$monday = new Carbon('this week'); 
$tuesday = new Carbon('this tuesday'); 
$wednesday = new Carbon('this wednesday'); 
$thursday = new Carbon('this thursday'); 
$friday = new Carbon('this friday'); 
$saturday = new Carbon('this saturday'); 
// Return object for charts.js 
return response()->json([ 
    'sunday'  => Event::where('page_id', 2)->where('created_at', 'like', $sunday->toDateString().'%')->get()->count(), 
    'monday'  => Event::where('page_id', 2)->where('created_at', 'like', $monday->toDateString().'%')->get()->count(), 
    'tuesday' => Event::where('page_id', 2)->where('created_at', 'like', $tuesday->toDateString().'%')->get()->count(), 
    'wednesday' => Event::where('page_id', 2)->where('created_at', 'like', $wednesday->toDateString().'%')->get()->count(), 
    'thursday' => Event::where('page_id', 2)->where('created_at', 'like', $thursday->toDateString().'%')->get()->count(), 
    'friday'  => Event::where('page_id', 2)->where('created_at', 'like', $friday->toDateString().'%')->get()->count(), 
    'saturday' => Event::where('page_id', 2)->where('created_at', 'like', $saturday->toDateString().'%')->get()->count() 
]); 

以上的回报如下:

{ 
    "sunday": 0, 
    "monday": 6, 
    "tuesday": 8, 
    "wednesday": 0, 
    "thursday": 0, 
    "friday": 7, 
    "saturday": 0 
} 

有几个问题,但是。应该总共有24条记录,但它只返回21.另外,每天进行个别查询似乎是一种可怕的做法。我想查询一次,然后每天过滤一次以设置总计/计数。返回过去7天事件的计数的首选和最准确的方法是什么?缺少的日子也需要返回0。

回答

1

我不是100%肯定我明白你的问题,但我相信这是你想要做什么......

$today = Carbon::today(); 
$events = Event::where('created_at', '>', $today->subDays(7))->get(); 
$totalCount = $events->count(); //Should return your total number of events from past 7 days 
$response = array(); 
$i = 0; 
while ($i < 7) { 
    $dayOfWeek = $today->subDays($i); 
    $eventsForThisDay = $events->where('created_at', $dayOfWeek); 
    $response[$dayOfWeek] = $eventsForThisDay->count(); 
    $i++; 
} 
return response()->json($response); 
+0

是的,这正是我试图完成,谢谢您! –