我正在尝试创建一个图表(ChartJS),它合并了我的数据库的2个表。
案例:
数据库
- 表格对象
--用户标识
--对象标识
--对象名称
--对象创建日期(年-月-日)
- 表格对象数量
--对象金额标识
-- object_id(对应于表对象)
--对象总数
我想创建一个显示object_amount / object_date图表;并且只在tableObject-〉user_id ==我的应用的user_id时显示。
这是我的问题。
因此,我的应用程序运行在Codeingniter上,这里是我的代码:
public function index() {
$objectsArray = array();
$objectsDates = [];
$objectsAmounts = [];
$this->db->select('*');
$this->db->from('objects');
$this->db->where('user_id', $this->session->userdata('user_id'));
$objectsDatesQuery = $this->db->get();
foreach ($objectsDatesQuery->result() as $objectsDatesQueryRow) {
$objectsDates['object_id'] = $objectsDatesQueryRow->object_id;
$objectsDates['date'] = $objectsDatesQueryRow->object_date_created;
$this->db->select('*');
$this->db->from('object_amounts');
$this->db->where('object_id', $objectsDates['object_id']);
$objectsAmountsQuery = $this->db->get();
foreach ($objectsAmountsQuery->result() as $objectsAmountsQueryRow) {
$objectsDates['object_date'] = $objectsDatesQueryRow->object_date_created;
$objectsAmounts['object_total'] = $objectsAmountsQueryRow->object_total;
$objectsArray = array(
'object_date' => $objectsDatesQueryRow->object_date_created,
'object_total' => $objectsAmounts['object_total'],
);
}
}
}
我的图表的代码JS:
var ctx = document.getElementById('myChart').getContext('2d');
ctx.height = 246;
var chartData = {"jsonarray": <?php echo json_encode($objectsArray); ?>};
var labels = <?php echo json_encode($objectsArray['object_date']) ?>;
var data = <?php echo json_encode($objectsArray['object_total']) ?>;
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'bar',
// The data for our dataset
data: {
labels: labels,
datasets: [
{
label: 'Object',
borderColor: "black",
color: 'red',
backgroundColor: "white",
height: 200,
pointRadius: 0,
data: data
}
]
},
options: {
plugins: {
legend: {
display: false
}
},
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
min: 0,
color: 'black'
},
x: {
min: 0,
color: 'black',
}
}
}
});
当我这样做
var_dump(json_encode($objectsArray))
我已经
string(55) "{"objet_date":"2022-03-29","object_total":"3500.00"}"
最后,我的图表:
Result of my chartJS
非常非常感谢你的任何帮助!
1条答案
按热度按时间b1uwtaje1#
您可能希望使用联接并在一个查询中获取数据:
这将从对象表中选择某个用户的所有对象,并从object_amount表中为每个对象查找相应的object_amount。
join
上的left outer
还包括没有相应object_amount的对象。我假设您希望显示每个object_date_created的object_totals的总和:
group_by
按日期对合计进行分组,SUM(oa.object_total)
对每个日期的合计进行求和,然后order_by
按日期对结果求和进行排序。在您的JavaScript中: