gpt4 book ai didi

laravel - 有没有办法在没有数据的情况下返回 0 几个月?

转载 作者:行者123 更新时间:2023-12-04 09:30:58 26 4
gpt4 key购买 nike

我正在使用 Chart.js 来显示每个月的交易总数(计数)。

$dataTotal = ModelName::select(DB::raw('count(id) as count'), DB::raw("MONTH(created_at)  as month")) 
->where('org_id', auth()->user()->org_id)
->where('result_code', 200)
->groupBy('month')
->orderBy('month')
->get()
->toArray();
查询本身是没问题的,除了如果一个月内没有记录则不返回 0的问题。那个月。这导致图形无法正确呈现。
有没有人对我如何实现它以便我收到完整的结果集有任何建议?
所需的格式是:
array (
0 =>
array (
'count' => 0,
'month' => 1,
),
1 =>
array (
'count' => 5,
'month' => 2,
),
2 =>
array (
'count' => 0,
'month' => 3,
),
3 =>
array (
'count' => 4,
'month' => 4,
),
4 =>
array (
'count' => 0,
'month' => 5,
),
5 =>
array (
'count' => 4,
'month' => 6,
),
6 =>
array (
'count' => 51225,
'month' => 7,
),
7 =>
array (
'count' => 4,
'month' => 8,
),
8 =>
array (
'count' => 0,
'month' => 9,
),
9 =>
array (
'count' => 0,
'month' => 10,
),
10 =>
array (
'count' => 0,
'month' => 11,
),
11 =>
array (
'count' => 0,
'month' => 12,
),

)

最佳答案

$monthlyArray = array();
$emptyMonth = array('count' => 0, 'month' => 0);
for($i = 1; $i <= 12; $i++){//generate an array with default values
$emptyMonth['month'] = $i;
$monthlyArray[$i-1] = $emptyMonth;

}

$dataTotal = ModelName::select(DB::raw('count(id) as count'), DB::raw("MONTH(created_at) as month"))
->where('org_id', auth()->user()->org_id)
->where('result_code', 200)
->groupBy('month')
->orderBy('month')// you don't really need this one
->get()
->toArray();//fetch the results

foreach($dataTotal as $key => $array){//add the results to the default array
$monthlyArray[$array['month']-1] = $array;
}
//monthlyArray contains the data

关于laravel - 有没有办法在没有数据的情况下返回 0 几个月?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62844815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com