CakePhp3 - 在 ChartJs 上显示值

CakePhp3 - Showing values on ChartJs

我是 CakePhP3 的新手,我正在尝试在 ChartJs 中生成一些报告。

我有一个叫 "Incomes" 的 table。

CREATE TABLE `incomes` (
 `id` bigint(100) NOT NULL AUTO_INCREMENT,
 `title` varchar(500) NOT NULL,
 `description` varchar(5000) NOT NULL,
 `branch_id` bigint(100) NOT NULL,
 `amount` double NOT NULL,
 `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE 
 CURRENT_TIMESTAMP,
 `comments` varchar(50000) DEFAULT NULL,
 `status` tinyint(1) NOT NULL,
 PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

我想在图表上显示每月产生的总收入 金额 值。例如 - 1 月 10,000,3 月 20,000。

// Get context with jQuery - using jQuery's .get() method.
var areaChartCanvas = $("#areaChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var areaChart = new Chart(areaChartCanvas);

var areaChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July","August", "September", "October", "November", "December"],
  datasets: [
    {
      label: "Electronics",
      fillColor: "rgba(210, 214, 222, 1)",
      strokeColor: "rgba(210, 214, 222, 1)",
      pointColor: "rgba(210, 214, 222, 1)",
      pointStrokeColor: "#c1c7d1",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: [65, 59, 80, 81, 56, 55, 40]
    }
  ]
};

我如何加载 Incomes 模型 PagesController 并在图表上显示它们?我是将值作为 JSON 发送还是程序是什么?

你可以这样做

In Controller

        $this->loadModel('Incomes');
        $incomes = $this->Incomes->find('list', [
            'keyField' => 'month',
            'valueField' => 'amount',
            'fields'=>[
                'month' => 'MONTHNAME(created)',
                'amount' => 'SUM(amount)'
            ],
            'group' => ['month'],
            'order'=>['MONTH(created)'=>'ASC'],
        ])->toArray();

        $months = json_encode(array_keys($incomes));
        $amounts = json_encode(array_values($incomes));
        $this->set('months', $months);
        $this->set('amounts', $amounts);

In view

// Get context with jQuery - using jQuery's .get() method.
var areaChartCanvas = $("#areaChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var areaChart = new Chart(areaChartCanvas);

var areaChartData = {
  labels: <?= $months; ?>,
  datasets: [
    {
      label: "Electronics",
      fillColor: "rgba(210, 214, 222, 1)",
      strokeColor: "rgba(210, 214, 222, 1)",
      pointColor: "rgba(210, 214, 222, 1)",
      pointStrokeColor: "#c1c7d1",
      pointHighlightFill: "#fff",
      pointHighlightStroke: "rgba(220,220,220,1)",
      data: <?= $amounts; ?>
    }
  ]
};