Carbon Skip определенный месяц

Есть ли способ пропустить определенный месяц? Мне просто нужно показать январь, февраль, сентябрь, октябрь, ноябрь и декабрь.

Это мой код:

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

Есть ли способ пропустить или не показывать некоторые из конкретных событий месяца?

2 ответа

вы можете использовать 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();

или просто сделайте это, используя функцию mysql raw и Month :

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

Вы можете сделать этот фильтр в файле foreach. Предполагая, что у вас есть месяц в виде числа в базе данных:

      foreach ($data as $key => $array) {
   if(in_array($array->month, [1,2,9,10,11,12]))
   {
       $monthlyArray[$array->month - 1] = $array;
    }
}
Другие вопросы по тегам