下午好。 我正在使用Chart JS,并且试图显示条形图中每列的现有总数。
在后端,我使用Laravel作为框架,并通过$datacount
变量从控制器传递数据。
这是我在控制器中的查询:
$datacount = DB::table('topics')
->leftJoin('proposals_topics', 'topics.id', '=', 'proposals_topics.topic_id')
->select('topics.name as tpcname', 'proposals_topics.topic_id', \DB::raw('count(topic_id) as total'))
->groupBy('topics.name', 'proposals_topics.topic_id')
->orderBy('topic_id', 'desc')
->get();
我在此脚本中收到的变量的数据:
<script>
var datacount = <?= json_encode($datacount, JSON_PRETTY_PRINT); ?>;
console.log(datacount);
// Bar chart
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["Compras y Contrataciones", "Acceso a la Información", "Educación", "Organismos de Control", "Servicio Civil", "Infraestructura", "Energía", "Gestión Financiera", "Salud", "Agua"],
datasets: [
{
label: "Cantidad generada",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#ffc344","#ff8e17", "#ff4cd8","#ffea4c","#b7ff4c"],
data: [datacount.total]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Datos generados por eje temático.'
}
}
});
</script>
我正在控制台中接收结果,但是无法显示数组的数据。
答案 0 :(得分:1)
在阅读了一些有关Laravel文档和Javascript的知识之后,我找到了一种在图形上绘制数据的解决方案。
在脚本中,我根据https://laravel.com/docs/5.7/blade#if-statements的循环文档构造了foreach。
<script>
//console.log(datacount);
// Bar chart
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: [
@foreach($datacount as $dt)
"{{ $dt->tpname }}",
@endforeach
],
datasets: [
{
label: "Cantidad generada",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#ffc344","#ff8e17", "#ff4cd8","#ffea4c","#b7ff4c"],
data: [
@foreach($datacount as $dt)
{!! $dt->total !!},
@endforeach
],
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Ejes temáticos por cantidad de propuestas.'
}
}
});
</script>
还在https://quickadminpanel.com/pages/reports-generator-module
上看到了一些示例。答案 1 :(得分:0)
您可以使用以下方法将来自PHP脚本的数据放在数据字段中: