问题描述
我想在服务器端处理生成的 Eloquent 结果数据,然后将其显示给 Chart.js,所有数据都是从数据库动态生成的。
我在尝试为相同的 subtotal
和 items_name
增加 sales_date
值,然后从数据库中显示标签、x 和 y 轴时遇到了一些问题。
这是我的 Eloquent ->toArray()
回复:
array:5 [
0 => array:3 [
"sales_date" => "2021-02-25"
"subtotal" => 800000
"items_name" => "Kitchen Set"
],1 => array:3 [
"sales_date" => "2021-02-25"
"subtotal" => 2000000
"items_name" => "Kitchen Set"
],2 => array:3 [
"sales_date" => "2021-02-26"
"subtotal" => 1000000
"items_name" => "Chair"
],3 => array:3 [
"sales_date" => "2021-02-26"
"subtotal" => 1000000
"items_name" => "Chair"
],4 => array:3 [
"sales_date" => "2021-02-27"
"subtotal" => 1000000
"items_name" => "Stove"
],]
我也尝试在服务器端使用 ->map()
函数:
$processed['labels'] = [];
$results->map( function( $val,$key ) use(&$processed) {
$processed['labels'][$key] = $val->sales_date;
if( $processed['labels'][$key] === $val->sales_date) {
$processed['datas'][$key] = ["data" => $val->subtotal,"label" => $val->varieties_name];
}
});
但我对 Chart.js 所需的数据结构感到困惑,如果没有像下图这样的访问者,则会像 Google Analytics 图表一样显示“0”销售额:
这是 Chart.js 中的一些预期结果(x axis
应该与数据集相同):
这是我硬编码的 Chart.js
$.ajax({
url : "{{ route('home.selling') }}",type : "GET",success : function( res ){
var selling_chart = new Chart(document.getElementById("selling_per_items"),{
type: 'line',data: {
labels: ['2021-02-24','2021-02-25','2021-02-26','2021-02-27'],datasets: [{
data : [ '2800000' ],label : 'Kitchen Set',lineTension: 0,fill : false,borderColor : dynamicColors(),},{
data : [ '2000000' ],label : 'Chair',{
data : [ '100000' ],label : 'Stove',}]
},options: {
title: {
display: false
},responsive: true,maintainAspectRatio : false,scales: {
xAxes: [{
stacked: true,}],yAxes: [{
stacked: true,ticks: {
beginAtZero: true
}
}]
}
});
}
});
我的环境:
jQuery : v3.4.1
Chart.js : v2.8.0
Laravel : 8.x
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)