简体   繁体   English

Canvas js如何将数据从数据库推送到Yii2中的图表

[英]Canvas js how to push data from database to chart in Yii2

I am working on yii2 .我正在研究yii2 I have installed the canvas js library, tried to run the sample chart example.我已经安装了 canvas js 库,尝试运行示例图表示例。 Now I want to push data from my database.现在我想从我的数据库中推送数据。 I am able to view single data from my DB, but I want to put all the data when the database is updated ie I have a button and on that button click my table is updated during that period I want to update my chart also to show the updated value(s).我可以从我的数据库中查看单个数据,但是我想在数据库更新时放置所有数据,即我有一个按钮,然后在该按钮上单击我的表在此期间更新我还想更新我的图表以显示更新的值。

Note: Chart should show the trend注意:图表应显示趋势

Below is my controller code from which I am inserting the data into my table下面是我将数据插入表中的 controller 代码

public function actionData()
{
    try {
        $cust_met_data = Yii::$app->db->createCommand(
            "SELECT m.`meter_id` , m.`msn` , 
                  m.`cust_id` , m.`device_id` FROM `mdc_meter_cust_rel` m ")->queryAll();
    } catch (Exception $e) {
    }

    $slave_id = $cust_met_data[0]['device_id'];
    $address = 0;
    $count = 14;
    $msn = $cust_met_data[0]['msn'];
    $cust_id = $cust_met_data[0]['cust_id'];

    // my base URL
    $api_url = 'https://localhost:44337/api/rtu/GetData/' . $slave_id . '/' . $address . '/' . $count;


    $curl = curl_init($api_url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $curl_response = curl_exec($curl);

    $json = json_decode($curl_response);

    if($json->{0} == '06')
    {
        Yii::$app->getSession()->setFlash('error', '
 <div class="alert alert-error alert-dismissable">
 <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
 <strong>No Communication! </strong> Meter Data is Unavailable.</div>');

        return $this->redirect(['index']);
    }
    else
    {
        $vol_1 = $json->{0};
        $vol_2 = $json->{1};
        $vol_3 = $json->{2};
        $curr_1 = $json->{3};
        $curr_2 = $json->{4};
        $curr_3 = $json->{5};
        $kwh = $json->{6};

        $model = new MdcmetersData();
        $model->load(Yii::$app->request->post());
        $model->data_date_time = date('Y-m-d H:i:s');
        $model->device_id = $slave_id;
        $model->msn = $msn;
        $model->cust_id = $cust_id;
        $model->voltage_p1 = $vol_1;
        $model->voltage_p2 = $vol_2;
        $model->voltage_p3 = $vol_3;
        $model->current_p1 = $curr_1;
        $model->current_p2 = $curr_2;
        $model->current_p3 = $curr_3;
        $model->kwh = $kwh;

        if($model->save())
        {
            return $this->redirect(['index', 'model' => $model]);
        }
        else
        {
            return $this->redirect(['index']);

        }

    }




}

Index.php索引.php

<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<?PHP
  $model = $dataProvider->getModels()[0];
  $model['data_date_time'];

  $dataPoints1 = array(
  array("label"=> $model['data_date_time'], "y"=> $model['kwh']),

  );

 ?>
<div id="chartContainer1" style="width: 100%; height: 300px;display: inline-block;"></div>
<p>
    <?= Html::a('Get Meter Data', ['data'], ['class' => 'btn btn-success']) ?>
</p>



<script>
window.onload = function () {
 var chart = new CanvasJS.Chart("chartContainer1", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "kWh of Meter"
    },
    legend:{
        cursor: "pointer",
        verticalAlign: "center",
        horizontalAlign: "right",
        itemclick: toggleDataSeries
    },
    data: [{
        type: "column",
        name: "kwh",
        indexLabel: "{y}",

        showInLegend: true,
        dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?>
    }
    ]
});
chart.render();

function toggleDataSeries(e){
    e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
    chart.render();
}
};

Chart output图表 output

在此处输入图像描述

It's a single value shown but in actual I have more than one value.这是一个显示的值,但实际上我有多个值。

I have searched for the solution but all I found is the traditional way to push data.我已经搜索了解决方案,但我发现的只是推送数据的传统方式。 ie in PHP, I have to run a query and then perform an action on that.即在 PHP 中,我必须运行查询,然后对其执行操作。 A sample is shown here PHP Chart Data from Database此处显示了一个示例PHP 来自数据库的图表数据

How can I do it?我该怎么做? Any help would be highly appreciated任何帮助将不胜感激

Because you are getting the first record to populate from the $dataProvider因为您正在从$dataProvider获得第一条记录

$model = $dataProvider->getModels()[0];

it should be它应该是

$model = $dataProvider->getModels();

Apart from it I would keep things simple and pull the data by making a separate static function in the model and call it from the controller and pass the data on to the view to the charts to display. Apart from it I would keep things simple and pull the data by making a separate static function in the model and call it from the controller and pass the data on to the view to the charts to display.

You're only asking for the first record.你只要求第一条记录。 You will need to get all of them.您将需要获得所有这些。

Easiest solution is:最简单的解决方案是:

<?PHP
  // final data array
  $dataPoints1 = [];
  // loop through dataprovider for every $model
  forech(dataProvider->getModels() as $index => $model) {
    // data gets added to specific keys 
    $array['label'] = $model['data_date_time'];
    $array['y'] = $model['kwh'];
    // for every $model a sub array gets added
    $dataPoints1[$index] = $array;
  }
 ?>

But it's not pretty.但这并不漂亮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM