CakePhp3 - 在ChartJ上显示值

时间:2017-05-04 07:47:26

标签: javascript cakephp cakephp-2.0 cakephp-3.0 chart.js

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

我有一张名为“收入”的表格。

treelib

我希望在图表上显示每月生成的总收入金额值。例如 - 1月1日,3月2,000日。

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;

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

1 个答案:

答案 0 :(得分:2)

你可以这样做

  

在控制器

        $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);
  

在视图中

// 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; ?>
    }
  ]
};