You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chart.js中按月份展示多产品销售收益数据集

多产品月度收益柱状图实现方案

1. 调整后端数据统计逻辑

首先需要修改数据查询,从「按月统计总收益」改为「按月+产品分组统计收益」,再整理成每个产品对应各月份的收益数组:

// 获取所有不重复的产品名称
$products = \App\Models\Sale::distinct()->pluck('products')->toArray();

// 按月份和产品分组统计收益
$salesData = \App\Models\Sale::selectRaw('MONTH(created_at) as month, products, SUM(earnings) as earnings')
    ->groupBy('month', 'products')
    ->orderBy('month')
    ->get();

// 初始化1-12月的收益数据(默认0)
$months = range(1, 12);
$monthlyData = [];
foreach ($products as $product) {
    $productEarnings = [];
    foreach ($months as $month) {
        $match = $salesData->where('month', $month)->where('products', $product)->first();
        $productEarnings[] = $match ? $match->earnings : 0;
    }
    $monthlyData[$product] = $productEarnings;
}

// 生成月份标签(如"1月"、"2月")
$monthLabels = array_map(function($m) {
    return date('n月', mktime(0,0,0,$m,1));
}, $months);

2. 修改UserChart类配置

更新Chart类,支持多数据集(每个产品对应一个数据集):

namespace App\Charts;

use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class UserChart extends Chart
{
    public function build($monthLabels, $monthlyData)
    {
        // 设置X轴月份标签
        $this->labels($monthLabels);

        // 为每个产品添加独立数据集
        foreach ($monthlyData as $productName => $earnings) {
            $this->dataset($productName, 'bar', $earnings)
                 ->backgroundColor($this->generateColor())
                 ->borderColor($this->generateColor(true))
                 ->borderWidth(1);
        }

        // 配置图表基础选项
        $this->options([
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                    'title' => ['display' => true, 'text' => '收益']
                ],
                'x' => [
                    'title' => ['display' => true, 'text' => '月份']
                ]
            ]
        ]);
    }

    // 生成随机颜色(数据集用半透明,边框用实色)
    private function generateColor($isBorder = false)
    {
        $hex = sprintf('#%06X', mt_rand(0, 0xFFFFFF));
        return $isBorder ? $hex : $hex . '80';
    }
}

3. 控制器传递数据到视图

在控制器中调用Chart类的build方法,传入整理好的标签和数据:

use App\Charts\UserChart;

public function dashboard(UserChart $chart)
{
    // 这里放入第一步的查询逻辑,得到$monthLabels和$monthlyData
    
    $chart->build($monthLabels, $monthlyData);
    return view('dashboard', compact('chart'));
}

4. Blade视图无需修改

保持原有渲染代码即可:

<div class="chart-container">
    {!! $chart->render() !!}
</div>

内容的提问来源于stack exchange,提问作者NeedHalp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 20:50:25