Carbon 跳过某月

Carbon Skip certain month

有没有办法跳过某个月份?我只需要显示一月、二月、九月、十月、十一月和十二月。

这是我的代码:

$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');

有没有办法跳过或不显示某些特定的月份?

您可以在 foreach 中创建此过滤器。假设您在数据库中将月份作为数字:

foreach ($data as $key => $array) {
   if(in_array($array->month, [1,2,9,10,11,12]))
   {
       $monthlyArray[$array->month - 1] = $array;
    }
}

你可以使用 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 和 Month mysql 函数:

  $query->whereIn(DB::raw('MONTH(created_at)'),[1,2,3,9]);