【问题标题】:Carbon Skip certain month碳跳过特定月份
【发布时间】:2022-01-02 18:21:54
【问题描述】:

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

这是我的代码:

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

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

【问题讨论】:

    标签: laravel eloquent php-carbon carbon


    【解决方案1】:

    你可以使用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]);
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 非常感谢它的工作!
      • 很高兴听到这个消息
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      相关资源
      最近更新 更多