微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Chart.js 在显示到图表之前在服务器端处理数据

如何解决Chart.js 在显示到图表之前在服务器端处理数据

我想在服务器端处理生成的 Eloquent 结果数据,然后将其显示给 Chart.js,所有数据都是从数据库动态生成的。

我在尝试为相同的 subtotalitems_name 增加 sales_date 值,然后从数据库显示标签、x 和 y 轴时遇到了一些问题。

这是我的 Eloquent ->toArray() 回复

array:5 [
  0 => array:3 [
    "sales_date" => "2021-02-25"
    "subtotal" => 800000
    "items_name" => "Kitchen Set"
  ],1 => array:3 [
    "sales_date" => "2021-02-25"
    "subtotal" => 2000000
    "items_name" => "Kitchen Set"
  ],2 => array:3 [
    "sales_date" => "2021-02-26"
    "subtotal" => 1000000
    "items_name" => "Chair"
  ],3 => array:3 [
    "sales_date" => "2021-02-26"
    "subtotal" => 1000000
    "items_name" => "Chair"
  ],4 => array:3 [
    "sales_date" => "2021-02-27"
    "subtotal" => 1000000
    "items_name" => "Stove"
  ],]

我也尝试在服务器端使用 ->map() 函数

$processed['labels']  =   [];

$results->map( function( $val,$key ) use(&$processed) {
    $processed['labels'][$key]  =   $val->sales_date;

    if( $processed['labels'][$key] === $val->sales_date) {
        $processed['datas'][$key]   =   ["data" => $val->subtotal,"label" => $val->varieties_name];
    }
});

但我对 Chart.js 所需的数据结构感到困惑,如果没有像下图这样的访问者,则会像 Google Analytics 图表一样显示“0”销售额:

Analytics chart

这是 Chart.js 中的一些预期结果(x axis 应该与数据集相同):

enter image description here

这是我硬编码的 Chart.js

$.ajax({
    url     :   "{{ route('home.selling') }}",type    :   "GET",success :   function( res ){
        var selling_chart = new Chart(document.getElementById("selling_per_items"),{
            type: 'line',data: {
                labels: ['2021-02-24','2021-02-25','2021-02-26','2021-02-27'],datasets: [{
                    data   : [ '2800000' ],label  : 'Kitchen Set',lineTension: 0,fill   : false,borderColor  : dynamicColors(),},{
                    data   : [ '2000000' ],label  : 'Chair',{
                    data   : [ '100000' ],label  : 'Stove',}]
            },options: {
                title: {
                    display: false
                },responsive: true,maintainAspectRatio : false,scales: {
                xAxes: [{
                    stacked: true,}],yAxes: [{
                    stacked: true,ticks: {
                        beginAtZero: true
                    }
                }]
            }
        });
    }

});

我的环境:

jQuery : v3.4.1
Chart.js : v2.8.0
Laravel : 8.x

谢谢

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。