首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从模型那里得到7天以上的数据?

从模型那里得到7天以上的数据?
EN

Stack Overflow用户
提问于 2016-10-04 15:17:26
回答 1查看 3.6K关注 0票数 0

我试图查询我的模型,并将一个对象返回给chart.js

代码语言:javascript
复制
// 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()
]);

上述内容返回以下内容:

代码语言:javascript
复制
{
  "sunday": 0,
  "monday": 6,
  "tuesday": 8,
  "wednesday": 0,
  "thursday": 0,
  "friday": 7,
  "saturday": 0
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-04 18:39:23

我不能百分之百肯定我理解你的问题,但我相信这就是你想要做的.

代码语言:javascript
复制
$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);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39856034

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档