从模型获取过去7天的数据? [英] Get Past 7 Days Data From Model?

查看:59
本文介绍了从模型获取过去7天的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查询我的模型并返回一个对象以馈送给chart.js

I am trying to query my model and return an object to feed to 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()
]);

以上内容返回以下内容:

The above returns the following:

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

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

There are a few issues however. There should be a total of 24 records however it is only returning 21. Also, it seems like horrible practice to make individual queries for each day. I'd like to query once and then filter down for each day to set a total tally/count. What would be the preferred and most accurate method to return a count of the past 7 days of events? Days missing need to return 0 as well.

推荐答案

我不是100%确信我理解您的问题,但是我相信这就是您要尝试做的...

I'm not 100% sure I understand your question, but I believe this is what you're trying to do...

$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);

这篇关于从模型获取过去7天的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆