【发布时间】:2016-10-04 15:17:26
【问题描述】:
我正在尝试查询我的模型并返回一个对象以提供给 chart.js
// 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。
【问题讨论】:
标签: laravel laravel-5 eloquent