Laravel中如何循环ChartJS数据集?现有代码问题求助
解决Laravel中ChartJS多系列柱状图数据循环问题
问题根源
原代码的核心问题:
- Controller将所有
hasil_keputusan和统计值合并到单一数组,未按每个hasil_keputusan作为独立系列拆分数据 - ChartJS配置仅使用单个dataset,无法渲染多系列柱状图
- 存在N+1查询问题(每个
umur发起一次数据库查询),效率低下
修复方案
1. 优化Model查询(减少N+1)
修改Model,一次性获取所有所需数据,避免多次查询数据库:
public function getGrafikData($tanggal) { return DB::table('riwayat') ->select('umur', 'hasil_keputusan', DB::raw('COUNT(id_riwayat) as jml_riwayat')) ->where('tanggal_riwayat', $tanggal) ->groupBy('umur', 'hasil_keputusan') ->get(); } // 获取所有唯一的umur作为x轴标签 public function getUmurLabels($tanggal) { return DB::table('riwayat') ->select('umur') ->where('tanggal_riwayat', $tanggal) ->groupBy('umur') ->pluck('umur') ->toArray(); } // 获取所有唯一的hasil_keputusan作为系列标签 public function getHasilLabels($tanggal) { return DB::table('riwayat') ->select('hasil_keputusan') ->where('tanggal_riwayat', $tanggal) ->groupBy('hasil_keputusan') ->pluck('hasil_keputusan') ->toArray(); }
2. 重构Controller数据结构
重新组织数据,让每个hasil_keputusan对应一个独立系列,每个系列的data数组与x轴的umur标签一一对应(无数据的位置自动补0):
$tanggal = "2022-08-10"; // 获取基础数据 $umurLabels = $this->m_dashboard->getUmurLabels($tanggal); $hasilLabels = $this->m_dashboard->getHasilLabels($tanggal); $rawData = $this->m_dashboard->getGrafikData($tanggal); // 把原始数据转成关联数组,方便快速查找 $dataMap = []; foreach ($rawData as $item) { $dataMap[$item->umur][$item->hasil_keputusan] = $item->jml_riwayat; } // 构建ChartJS需要的数据集 $datasets = []; // 定义不同系列的颜色(可按需扩展) $colors = ['rgb(255, 99, 132)', 'rgb(54, 162, 235)', 'rgb(255, 206, 86)', 'rgb(75, 192, 192)']; foreach ($hasilLabels as $index => $hasil) { $data = []; foreach ($umurLabels as $umur) { // 存在数据则取对应值,否则补0 $data[] = isset($dataMap[$umur][$hasil]) ? $dataMap[$umur][$hasil] : 0; } $datasets[] = [ 'label' => $hasil, 'backgroundColor' => $colors[$index % count($colors)], 'borderColor' => $colors[$index % count($colors)], 'data' => $data, 'borderWidth' => 1 ]; } $chartData = [ 'labels' => $umurLabels, 'datasets' => $datasets ]; return view('admin.dashboard', [ 'chart_data' => json_encode($chartData) ]);
3. 调整View的ChartJS配置
直接使用整理好的数据集,无需手动拼接:
var chartData = JSON.parse('<?php echo $chart_data; ?>'); const config = { type: 'bar', data: chartData, options: { responsive: true, scales: { y: { beginAtZero: true, title: { display: true, text: '数量' } }, x: { title: { display: true, text: '年龄' } } } } }; new Chart(document.getElementById('myChart'), config);
关键说明
- 优化后的数据结构完全匹配ChartJS多系列柱状图的要求:每个系列对应一个
dataset,包含独立标签、颜色和与x轴标签一一对应的数据 - 解决了N+1查询问题,仅需3次数据库查询即可获取所有数据
- 自动补0确保每个系列的数据长度与x轴标签一致,避免图表渲染异常
内容的提问来源于stack exchange,提问作者Sukmo Abadii
相关产品推荐
相关产品推荐

