グラフのラベルとデータを動的にすることが必要でした。Laravel 5.4 ChartJs - ラベル/データとしてコレクション/配列を使用する
は、物事を始めるために、私は私のController
にsearch
と呼ばれる機能を持っており、それがこのようなクエリがあります:チャートを持っている
$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>
また、$format
を使用して、販売分析のperiod
をCarbon
で解析する予定です。だから私はこの構文を使用するのではと思った:
{{\Carbon\Carbon::parse($collection->period)->format($format)}}
bottomlineは、私がChartJsのlabel
とdata
ためcollection
を使用するつもりのですか、です。
1次元配列として返すだけです – connormcwood
' - > toArray()'を追加するとコレクションが配列に変換されますか?その後、スクリプトでどのように適用しますか? –