我希望圖表的標籤和數據是動態的。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>
另外,銷售分析的period
將由Carbon
解析,使用$format
。所以,我想用這個語法:
{{\Carbon\Carbon::parse($collection->period)->format($format)}}
的底線是,我要怎麼使用collection
爲label
和ChartJs的data
。
你只需要將它作爲一維數組返回 – connormcwood
加入' - > toArray()'會將集合轉換爲數組嗎?之後,我將如何將其應用於腳本中? –