2017-08-31 34 views
0

我希望圖表的標籤和數據是動態的。Laravel 5.4 ChartJs - 使用集合/數組作爲標籤和數據

爲了讓事情開始,我有一個叫我Controllersearch功能,它有這樣的查詢:

$total_cost = DB::raw('SUM(qty * cost) as total_cost'); 
$total_grossrev = DB::raw('(SUM(price * qty)) as total_grossrev'); 
$total_profit = DB::raw('(SUM(price * qty)) - (SUM(qty * cost)) as total_profit'); 

$period = DB::raw('date(created_at) as period'); 
$format = 'j F Y h:i A'; 

$salesanalysis = DB::table('orders') 
    ->whereDate('created_at','>=', $request->datefrom) 
    ->whereDate('created_at', '<=', $request->dateto) 
    ->where('status', 'served') 
    ->select($total_cost, $total_grossrev, $total_profit, $period, 'created_at') 
    ->groupBy('period') 
    ->get(); 

而且在我的劇本有圖表,這是我的結構:

<script src="{{ asset('js/Chart.min.js') }}"></script> 

<script> 
    let salesAnalysisChart = document.getElementById('salesAnalysisChart').getContext('2d'); 

    let barChart = new Chart(salesAnalysisChart, { 
     responsive: true, 
     type:'bar', 
     data:{ 
      labels:[ //period of salesanalysis ], 
      datasets:[{ 
       label:'Sales', 
       data:[ 
        // total_profit of salesanalysis 
       ], 
       backgroundColor: 'rgba(73, 187, 235, 0.7)', 
       hoverBorderWidth: 1, 
       hoverBorderColor: '#000' 
      }] 
     }, 
     options:{ 
      maintainAspectRatio: false, 
      scales: { 
       yAxes: [{ 
        ticks: { 
         beginAtZero: true, 
        } 
       }] 
      }, 

      legend:{ 
       position:'bottom', 
       display:false, 
      }, 

      layout:{ 
       padding: 0, 
      } 
     } 
    }); 
</script> 

另外,銷售分析的period將由Carbon解析,使用$format。所以,我想用這個語法:

{{\Carbon\Carbon::parse($collection->period)->format($format)}} 

的底線是,我要怎麼使用collectionlabel和ChartJs的data

+0

你只需要將它作爲一維數組返回 – connormcwood

+0

加入' - > toArray()'會將集合轉換爲數組嗎?之後,我將如何將其應用於腳本中? –

回答

0

不知何故,我設法解決了這個問題。

在我controller,我做了查詢,並把它轉換成數組:

$salesanalysisarray = DB::table('orders') 
        ->whereDate('created_at','>=', $request->datefrom) 
        ->whereDate('created_at', '<=', $request->dateto) 
        ->where('status', 'served') 
        ->select($total_cost, $total_grossrev, $total_profit, $period, 'created_at') 
        ->groupBy('period') 
        ->get() 
        ->toArray(); 

在我script,我初始化另一個array,做一個循環,每一個數據推入array本身:

var periodArray = new Array(); 
    var profitArray = new Array(); 
    var costArray = new Array(); 

    @forelse($salesanalysis as $analysis) 
    periodArray.push("{{\Carbon\Carbon::parse($analysis->created_at)->format($format)}}"); 
    profitArray.push("{{$analysis->total_profit}}"); 
    costArray.push("{{$analysis->total_cost}}"); 
    @empty 
    @endforelse 
0

在視圖的底部創建一個buildChart函數,該函數將標籤,數據和其他任何參數作爲參數。使用PHP implode方法傳遞它們並將刀片中的內爆變量返回到創建圖表的函數。

//View 
buildChart({{ $variable }}, ect) 
+0

'$ variable'被認爲是集合? –