使用碳仅获取 2 个月数据的收入图表

问题描述 投票:0回答:1

我有这个代码来显示收入图表栏,显示当前过去 11 个月的栏,但仅获取和显示过去 2 个月的数据

这是代码:

<---------


public function incomeChartData(): array
    {
        $manualPayment = Subscription::wherePaymentType('paid')
            ->whereYear('created_at', Carbon::now()->year)->get()
            ->groupBy(function ($q) {
                return Carbon::parse($q->created_at)->isoFormat('MMM');
            });

        $transactions = Transaction::whereStatus(1)
            ->whereYear('created_at', Carbon::now()->year)->get()
            ->groupBy(function ($q) {
                return Carbon::parse($q->created_at)->isoFormat('MMM');
            });

        $data = [];
        $periods = now()->startOfMonth()->subMonths(11)->monthsUntil(now());
        $labels = [];
        $dataset = [];
        $colors = [];
        $borderColors = [];
        foreach ($periods as $key => $period) {
            $month = $period->isoFormat('MMM');
            $labels[] = $month;
            $colors[] = getBGColors($key).')';
            $borderColors[] = getBGColors($key).', 0.75)';
            $amounts = isset($transactions[$month])
                ? $transactions[$month]->pluck('amount')->toArray() : [0];
            $amounts = isset($manualPayment[$month])
                ? array_merge($amounts, $manualPayment[$month]->pluck('payable_amount')->toArray()) : $amounts;
            $dataset[] = removeCommaFromNumbers(number_format(array_sum($amounts), 2));
        }

        $data['labels'] = $labels;
        $data['breakDown'][] = [
            'label' => __('messages.common.total_amount'),
            'data' => $dataset,
            'backgroundColor' => $colors,
            'borderColor' => $borderColors,
            'lineTension' => 0.5,
            'radius' => 4,
        ];

        return $data;
    }
}


--------->

请帮助我哪里错了以及如何显示每个月的数据?

我尝试使用碳来改变月份,但由于我是新手,我找不到解决方案。

我期待收入图表显示每个月的数据。

php laravel laravel-8
1个回答
0
投票

我从事过一个类似的项目,我需要制作图表栏。 Soo,这个查询对我有帮助。首先,我获取日期和价格,然后按月份对数据进行分组,并将它们传递到刀片文件中。

             $charges = DB::table('city_drivers')
            ->join('cities', 'city_drivers.city_id', '=', 'cities.id')
            ->where('city_drivers.user_id', $id) 
            ->select('city_drivers.date', 'cities.price')
            ->get();

        // Group the results by month
        $chargesData = $charges->groupBy(function ($item) {
            return Carbon::parse($item->date)->format('M');
        });

        $chargeMonths = [];
        $chargePrice = [];

        foreach ($chargesData as $chargeMonth => $values) {
            // Calculate the total price for the month
            $totalPrice = $values->sum('price');

            $chargeMonths[] = $chargeMonth;
            $chargePrice[] = $totalPrice;
        }

在刀片文件中

   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" crossorigin="anonymous"></script>
<script type="text/javascript">
    var _ycharge = JSON.parse('{!! json_encode($chargeMonths) !!}');
    var _xcharge = JSON.parse('{!! json_encode($chargePrice) !!}');
</script>

在JS中我使用了条形图

    Chart.defaults.global.defaultFontFamily = '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#292b2c';


var allMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// Create an array for prices, matching the order of allMonths
var prices = allMonths.map(function(month) {
  // Check if the current month is in _yticket
  var index = _ycharge.indexOf(month);
  if (index !== -1) {
    // If the month is in _yticket, use the corresponding price from _xticket
    return _xcharge[index];
  } else {
    // If the month is not in _yticket, use null as a placeholder
    return null;
  }
});

// Bar Chart Example
var ctx = document.getElementById("myCityChart");
var myBarChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: allMonths, // Show all months on the X-axis
    datasets: [{
      label: "Price",
      backgroundColor: "rgba(2,117,216,1)",
      borderColor: "rgba(2,117,216,1)",
      data: prices, // Use the prices array with placeholders for missing months
    }],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'category',
        time: {
          unit: 'month'
        },
        gridLines: {
          display: false
        },
        ticks: {
          maxTicksLimit: 12, // Show all months
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          maxTicksLimit: 9,
        },
        gridLines: {
          display: true
        }
      }],
    },
    legend: {
      display: false
    }
  }
});

我希望它有帮助。 :)

© www.soinside.com 2019 - 2024. All rights reserved.