【发布时间】:2019-11-25 02:46:16
【问题描述】:
我需要根据从 $request 获得的日期发送每个日期的观看次数。从我在控制器中的查询中,我得到如下图表的数据:
[{"time":"2016-05-01","count":2},{"time":"2016-05-02","count":3},{"time":"2016-05-03","count":7},{"time":"2016-05-07","count":3}]
对于该数据,我需要添加0 的缺失日期和查看次数。我正在尝试关注this example,但我似乎无法为我的示例实施此解决方案。这是我的方法:
public function timelines(Request $request){
$from = $request['from'];
$to = $request['to'];
$data = DB::table($request['option'])
->select(DB::raw('DATE(created_at) as time'), DB::raw('count(*) as count'))
->whereDate('created_at', '>=', date($from).' 00:00:00')
->whereDate('created_at', '<=', date($to).' 00:00:00')
->groupBy('time')
->get();
return json_encode($data);
}
更新代码:
public function timelines(Request $request){
$from = $request['from'];
$to = $request['to'];
$date = $from;
$data = [];
if ($request['option'] == 'time'){
$data = View::groupBy('time')
->orderBy('time', 'ASC')
->whereDate('created_at', '>=', date($from).' 00:00:00')
->whereDate('created_at', '<=', date($to).' 00:00:00')
->get([
DB::raw('Hour(created_at) as time'),
DB::raw('COUNT(*) as "count"')
]);
}
else {
while($date <= $to) {
$formattedDate = date('Y-m-d', strtotime($date));
$results = DB::table($request['option'])
->select(DB::raw('DATE(created_at) as time'), DB::raw('count(*) as count'))
->whereDate('created_at', '=', $formattedDate .' 00:00:00')
->groupBy('time')
->get();
if(count($results)) {
$data[] = [
'time' => $formattedDate,
'count' => $results[0]->count
];
} else {
$data[] = [
'time' => $formattedDate,
'count' => 0
];
}
$date = strtotime('+1 day', strtotime($formattedDate));
}
}
return json_encode($data);
}
这样我只计算我发送的第一个日期,例如:
[{"time":"2016-03-16","count":0}]
【问题讨论】:
-
[{"time":"2016-03-16","count":0}]-> 这是您拥有$request['option'] == 'time'或$request['option'] != 'time'时得到的结果吗? -
当我有 $request['option'] != 'time' 时会发生这种情况,但我已经想出了一个解决方案,并且一切正常,就像我设置的那样。
标签: php mysql eloquent laravel-5.2