你好我真的需要帮助标签不显示在图表中,我正在使用 Laravel Livewire 和 Chart Js 标签显示 4 [object Object] 其中 4 个项目正确但不显示名称
我想要做的是将课程名称作为标签,getRandomnumber 是该表中值的数量
这是我的代码 Livewire 视图
<div>
<div class="justify-content-end text-end" style="right:0;">
<select style="width: 9rem;">
<option value="{{ date('Y')}}">{{ date('Y')}}</option>
</select>
</div>
<canvas id="myChart"></canvas>
</div>
@once
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
@endpush
@endonce
@push('scripts')
<script>
const chart = new Chart(
document.getElementById('myChart'), {
type: 'bar',
data: {
labels: @json($labels),
datasets: @json($dataset)
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
Livewire.on('updateChart', data => {
chart.data = data;
chart.update();
});
</script>
@endpush
这是 Livewire 组件
<?php
namespace App\Http\Livewire\Chart;
use Livewire\Component;
use App\Models\Enrollment;
use Illuminate\Support\Facades\DB;
class ChartEnrollmentFirstYr extends Component
{
public array $dataset = [];
public array $labels = [];
public function mount()
{
$this->labels[] = $this->getLabels();
$this->dataset = [
[
'label' => 'Enrollees',
'backgroundColor' => '#1d7e43',
'data' => $this->getRandomData(),
],
];
$labels = $this->getLabels();
$dataset = [
[
'label' => 'Enrolless',
'backgroundColor' => '#1d7e43',
'data' => $this->getRandomData(),
],
];
$this->emit('updateChart', [
'datasets' => $dataset,
'labels' => $labels,
]);
}
private function getLabels()
{
$labels = [];
$alumni = DB::table('enrollments')
->join('academic_programs', 'academic_programs.id','=','enrollments.degree_id')
->select('academic_programs.program_abbv as course, DB::raw(count(enrollments.id) as total)')
->groupBy('academic_programs.program_abbv')
->orderBy('course')
->get();
foreach ($alumni as $alu)
{
$labels[]= $alu;
}
return $labels;
}
private function getRandomData()
{
$data = [];
$alumni = Enrollment::where('degree_id','!=',NULL)->orderBy('degree_id', 'ASC')->get();
foreach ($alumni as $alu => $values )
{
$data[]= $values;
}
return $data;
}
public function render()
{
return view('livewire.chart.chart-enrollment-first-yr');
}
}