我正在尝试使用一些数据集处理图表,但是为了提出这个问题,我只会包含一个。
目前我的控制器中有以下内容:
$maintenancesForklifts =
DB::table("equipment_attachments")
->join('equipment as equip', 'equip.id', '=', 'equipment_attachments.unitID')
->select(DB::raw('year(date) as year'), DB::raw("COUNT(*) as count"))
->where('attachmentCategory','Maintenance')
->where('equip.unit_type',3)
->orderBy(DB::raw("year(date)"))
->groupBy(DB::raw("year(date)"))
->get();
我会得到这个回复:
[{"year":2005,"count":2},{"year":2006,"count":2},{"year":2010,"count":4},{"year":2011,"count":1},{"year":2012,"count":2},{"year":2013,"count":1},{"year":2014,"count":10},{"year":2015,"count":7},{"year":2016,"count":6},{"year":2017,"count":19},{"year":2018,"count":4}]
正如你所看到的那样,如果我从2000年开始到现在,有几年不见了。你知道我怎么能返回结果,以便他们会回到零计数的年份吗?
答案 0 :(得分:0)
你可以这样做的一种方式:
$years = collect(range(2000, now()->format('Y')))->map(function ($year) use ($maintenancesForklifts) {
return $maintenancesForklifts->firstWhere('year', $year) ?? (object)['year' => $year, 'count' => 0];
});