【问题标题】:Get Past 7 Days Data From Model?从模型中获取过去 7 天的数据?
【发布时间】: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


    【解决方案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);
    

    【讨论】:

    • 是的,这正是我想要完成的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多