2016-10-04 59 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

是的,這正是我試圖完成,謝謝您! –

相關問題