[Laravel] calc表列特定范围问题 [英] [Laravel]calc table column specfic range question
问题描述
[更新]我在laravel学习数字总和.我想每月计算表的列总数.
[UPDATE] I'm studying number sum at laravel. I would like to calculate table's columns total amount every month.
我写了下面的代码,得到了dd结果(图像)
I wrote below code and I got this dd result (image)
public function count()
{
Contact::whereYear('created_at', 2021)
->orderBy('created_at')
->get()
->groupBy(function ($row) {
return $row->created_at->format('m');
})
->map(function ($day) {
// dd($day);
return $day->sum('q1a');
});
}
但是,我的刀片文件中只有白色空白页.
However I only get white blank page at my blade file.
我的刀片文件(count.blade.php)就是这样
My blade file(count.blade.php) is like this
<h3>{{ $q1a }}</h3>
您能教我正确的密码吗?
Could you teach me correct code please?
一件事,当我尝试求和时,我得到了这个错误
And one thing When I try to sum I got this error
警告:遇到的非数字值
Warning: A non-numeric value encountered
某些列不是数字,所以我想调整修复控制器代码.
some of column are not number so I would like to adjust fix controller code.
WEB.php
//calc total amount page
Route::get('count', 'ContactsController@count');
[更新]我用Dear OMR的答案写了下面的代码
[UPDATE] I wrote below code using Dear OMR's answer
public function count()
{
Contact::whereYear('created_at', 2021)
->orderBy('created_at')
->select(['id','sno','s_date', DB::raw("MonthName(created_at)as monthName"), DB::raw('sum(q1a)')])
->groupBy(['id','sno','s_date', 'monthName', 'q1a'])->get();
}
count.blade.php代码在下面
count.blade.php code is below
@foreach ($values as $value)
{{ $value->sumQ }}
@endforeach
这是当前的dd结果
推荐答案
您可以在DB阶段执行此操作,巫婆会更快:
you can do it in DB stage, witch would be faster:
$values= Contact::whereYear('created_at', 2021)
->orderBy('created_at')
->select(['id','sno','s_date', DB::raw("MonthName(created_at)as monthName"), DB::raw('sum(q1a) as sumQ ')])
->groupBy(['id','sno','s_date', 'monthName'])->get();
注释:添加到select语句中的任何列也应按语句分组添加.
note: any column you add it to select statement, should be also added in group by statement.
这篇关于[Laravel] calc表列特定范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!