有办法跳过某个月吗?我只需要展示一月,二月,九月,十月,十一月和十二月。
这是我的密码:
$emptyMonth = ['count' => 0, 'month' => 0];
for ($i = 1; $i <= 12; $i++) {
$emptyMonth['month'] = $i;
$monthlyArray[$i - 1] = $emptyMonth;
}
$data = DB::table('doc')
->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
->where('status', 'done')
->where('created_at', '>=', Carbon::parse('first day of january'))
->where('created_at', '<=', Carbon::parse('last day of december'))
->whereyear('created_at', Carbon::now())
->groupBy('month')
->orderBy('month')
->get()
->toarray();
foreach ($data as $key => $array) {
$monthlyArray[$array->month - 1] = $array;
}
$result = collect($monthlyArray)->pluck('count');
有没有一种方法可以跳过或不显示一些具体的一个月?
发布于 2021-11-24 11:05:04
您可以使用whereMonth
$data = DB::table('doc')
->select(DB::raw('count(*) as count,MONTH(created_at) as month'))
->where('status', 'done')
->where('created_at', '>=', Carbon::parse('first day of january'))
->where('created_at', '<=', Carbon::parse('last day of december'))
->whereyear('created_at', Carbon::now())
->where(function($query){
$query->whereMonth('created_at',1)
->orWhereMonth('created_at',2)
->orWhereMonth('created_at',9); // extra
})
->groupBy('month')
->orderBy('month')
->get()
->toarray();
或者简单地使用raw和月份 mysql函数进行操作:
$query->whereIn(DB::raw('MONTH(created_at)'),[1,2,3,9]);
发布于 2021-11-24 11:04:43
你可以在前排做这个过滤器。假设您将月份作为数据库中的一个数字:
foreach ($data as $key => $array) {
if(in_array($array->month, [1,2,9,10,11,12]))
{
$monthlyArray[$array->month - 1] = $array;
}
}
https://stackoverflow.com/questions/70094766
复制相似问题