从模型中获取过去7天的数据?

时间:2016-10-04 15:17:27

标签: laravel laravel-5 eloquent

我正在尝试查询我的模型并返回一个对象以提供给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。

1 个答案:

答案 0 :(得分:2)

我不是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);