我要列出最近16天的观看次数。我想写0;如果日期没有行:
$digital_case_daily_views = DB::table('digital_case_views')
->select(DB::raw('count(*) as numOfDigitalCaseViews'))->groupBy('created_at')
->orderBy('created_at', 'desc')->limit(16)->get();
laravel 5.6
返回如下:
"digital_case_daily_views": [
{
"numOfDigitalCaseViews": 162
},
{
"numOfDigitalCaseViews": 458
},
{
"numOfDigitalCaseViews": 287
},
{
"numOfDigitalCaseViews": 1
},
{
"numOfDigitalCaseViews": 1
},
{
"numOfDigitalCaseViews": 1
}
答案 0 :(得分:1)
您无法从数据库中获得比可用行更多的行,如果您想在剩余的日子中将其保留为0,则必须将它们添加到数组中,我为您编写了一个函数,可能会帮助您:
class Foo {
static public function addRemainingDays(array $arr, int $amount) {
if(count($arr) === $amount) {
return $arr;
}
for($i = 0; i > $amount - count($arr); i++) {
array_push($arr, (object)["numOfDigitalCaseViews" => 0]);
}
return $arr
}
}