首页 > 解决方案 > 如何从 mysql 查询在 laravel 中创建谷歌图表?

问题描述

试图解决这个问题,但缺乏好的文档/示例正在杀死我。我模拟我的方法的最佳示例在这里:

https://www.itsolutionstuff.com/post/laravel-5-line-chart-example-code-using-google-charts-apiexample.html

在我的 laravel web.php 中,我设置了这样的路由:

Route::get('/chart', 'ChartController@index');

这是我的 ChartController.index 代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Measurement;
use Illuminate\Support\Facades\Log;
use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class ChartController extends Controller
{
    public function index()
    {
        Log::debug('made it to ChartController.php');
        $tests = Measurement::where('test_id', '=', 49)
                    ->leftJoin('labs','lab_id','=','labs.id')
                    ->select('labs.dateEntered','value')
                    ->get();
        Log::debug("tests=" .$tests);

        $result[] = ['Date','Value'];
        foreach($tests as $key => $value) {
            $result[++$key] = [$value->dateEntered, (int)$value->value];
        }
        Log::debug("result=" .$result);
        return view('plot')
            ->with('tests',json_encode($result));
    }
}

这是 plot.blade.php 代码:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      var tests = <?php echo $tests; ?>;
      console.log(tests);
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable(tests);
        var options = {
          title: 'Laboratory Test Chart',
          curveType: 'function',
          legend: { position: 'bottom' }
        };
        var chart = new google.visualization.LineChart(document.getElementById('linechart'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="linechart" style="width: 900px; height: 500px"></div>
  </body>
</html>

这是日志输出:

[2020-02-14 01:35:46] laravel.DEBUG: 到 ChartController.php [2020-02-14 01:35:46] laravel.DEBUG: tests=[{"dateEntered":"2011-02 -05 00:00:00","value":"117"},{"dateEntered":"2011-07-29 00:00:00","value":"69"},{"dateEntered": "2011-10-28 00:00:00","value":"125"},{"dateEntered":"2012-04-28 00:00:00","value":"84"},{ "dateEntered":"1970-01-01 00:00:00","value":"95"},{"dateEntered":"2016-08-13 00:00:00","value":"189 "},{"dateEntered":"2017-11-17 00:00:00","value":"195"},{"dateEntered":"1970-01-01 00:00:00","value “:”127"},{"dateEntered":"1970-01-01 00:00:00","value":"127"}]

但这就是它所能得到的。它在第 47 行出现“数组到字符串转换”失败,这就是:

Log::debug("result=" .$result);

感觉就像我很接近,但就是无法克服这最后一个障碍。建议?

标签: phpmysqllaravelgoogle-visualization

解决方案


推荐阅读