我使用 Chart.js 显示每个月的预订数量。这是我的查询。它工作正常。 我的问题是,如果一个月内没有预订,那么它不会显示任何内容。没有零值。在图表上,我得到了这样的值
- 1 月 23 日
- 2 月 34 日
- 4 月 23 日
- 5 月 25 日
- 7 月 42 日
图表上显示了 3 月和 6 月。.如何在没有预订的月份获得零值..
$graph = DB::table('bookings')
->select(DB::raw('MONTHNAME(created_at) as month'), DB::raw("DATE_FORMAT(created_At,'%M %Y') as monthNum"), DB::raw('count(*) as totalbook'))
->groupBy('monthNum')
->orderBy('created_at', 'asc')
->get();
为了得到几个月,`
@foreach ($graph as $dat)
"{!! $dat->monthNum !!}",
@endforeach`
并获取预订号
@foreach ($graph as $dat)
{!! $dat->totalbook !!},
@endforeach
最佳答案
MySQL 不会填写不可用的月份,它只会根据可用的月份进行分组,然后为您提供这些结果。
你可以做的是使用 DatePeriod
和 Laravel 的 Collection
类:
$results = DB::table('bookings')
->selectRaw("DATE_FORMAT(created_At,'%Y-%m-01') as monthNum, count(*) as totalbook")
->orderBy('monthNum')
->groupBy('monthNum')
->get();
$results = collect($results)->keyBy('monthNum')->map(function ($item) {
$item->monthNum = \Carbon\Carbon::parse($item->monthNum);
return $item;
});
$periods = new DatePeriod($results->min('monthNum'), \Carbon\CarbonInterval::month(), $results->max('monthNum')->addMonth());
$graph = array_map(function ($period) use ($results) {
$month = $period->format('Y-m-d');
return (object)[
'monthNum' => $period->format('M Y'),
'totalbook' => $results->has($month) ? $results->get($month)->totalbook : 0,
];
}, iterator_to_array($periods));
请注意,我已经更新了查询中的 monthNum
,因为它稍后会重新格式化。
此外,您应该需要为此使用 Blade 原始标签({!!!!}
),因为 {{ $dat->totalbook }}
应该可以工作绝对没问题。
希望这对您有所帮助!
关于php - 如果 Count 为零,如何在 Laravel 中获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44808189/