美好的一天,我需要您的帮助/指导来使用 Laravel Filament 中的 Chartjs 创建堆叠条形图。我有一个名为“任务”的表,它与“客户”表有关系。每个表的字段如下
任务
客户
我想创建一个堆积条形图,显示每个客户的所有任务,按优先级分组。我有以下代码片段
$data = Tasks::select('clients.client_name as client_name', 'tasks.priority', DB::raw('COUNT(tasks.id) as task_count'))
->join('clients', 'tasks.client_id', '=', 'clients.id')
->groupBy('clients.client_name', 'tasks.priority')
->orderBy('clients.client_name')
->orderBy('tasks.priority')
->get();
// Prepare labels array
$labels = array_keys(reset($data));
// Prepare datasets array
$datasets = [];
foreach ($data as $client => $priorities) {
$dataset = [
'label' => $client,
'backgroundColor' => [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 206, 86, 0.8)',
'rgba(75, 192, 192, 0.8)'
],
'data' => array_values($priorities),
];
$datasets[] = $dataset;
}
return [
'datasets' => $datasets,
'labels' => $labels
];
<?php
namespace App\Filament\Widgets;
use App\Models\Tasks;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\DB;
class TasksByPriority extends ChartWidget
{
protected static ?string $heading = 'Tasks By Priority';
public function getDescription(): ?string
{
return 'Summary of tasks created by priority';
}
protected static ?string $maxHeight = '300px';
protected static ?string $pollingInterval = null;
protected function getData(): array
{
$data = Tasks::select('clients.client_name as client_name', 'tasks.priority', DB::raw('COUNT(tasks.id) as task_count'))
->join('clients', 'tasks.client_id', '=', 'clients.id')
->groupBy('clients.client_name', 'tasks.priority')
->orderBy('clients.client_name')
->orderBy('tasks.priority')
->get();
// Prepare labels array
$labels = array_keys(reset($data));
// Prepare datasets array
$datasets = [];
foreach ($data as $client => $priorities) {
$dataset = [
'label' => $client,
'backgroundColor' => [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 206, 86, 0.8)',
'rgba(75, 192, 192, 0.8)'
],
'data' => array_values($priorities),
];
$datasets[] = $dataset;
}
return [
'datasets' => $datasets,
'labels' => $labels
];
}
protected function getType(): string
{
return 'bar';
}
}
我成功了。
protected static ?array $options = [
'scales' => [
'x' => [
'stacked' => true,
],
'y' => [
'stacked' => true,
],
],
];