Laravel统计一段时间间隔的数据方法(2)

 public function numberCount()
 {
  $days = request('days', 7);

  $range = Carbon::today()->subDays($days);

  $day_stats = Customer::where('created_at', '>=', $range)
   ->groupBy('date')
   ->orderBy('date', 'DESC')
   ->get([
    \DB::raw('DATE_FORMAT(created_at,\'%Y-%m-%d\') as date,SUM(CASE WHEN customer_type = 1 THEN 1 ELSE 0 END) AS customer,SUM(CASE WHEN customer_type = 2 THEN 1 ELSE 0 END) AS teacher'),
   ])
   ->toJSON();

  $week_stats = Customer::groupBy('week')
   ->orderBy('week', 'DESC')
   ->get([
    \DB::raw('DATE_FORMAT(created_at,\'%Y W%u\') as week,SUM(CASE WHEN customer_type = 1 THEN 1 ELSE 0 END) AS customer, SUM(CASE WHEN customer_type = 2 THEN 1 ELSE 0 END) AS teacher'),
   ])
   ->toJSON();
  // dd($week_stats);

  // \DB::enableQueryLog();
  $month_stats = Customer::groupBy('month')
   ->orderBy('month', 'DESC')
   ->get([
    \DB::raw('DATE_FORMAT(created_at,\'%Y-%m\') as month,SUM(CASE WHEN customer_type = 1 THEN 1 ELSE 0 END) AS customer,SUM(CASE WHEN customer_type = 2 THEN 1 ELSE 0 END) AS teacher'),
   ])
   ->toJSON();
  // dd(\DB::getQueryLog());
  // dd($week_stats, $month_stats);
  $data = $this->getNumber();
  // dd($day_stats, $week_stats, $month_stats, $data);
  return view('admin.numberCount', compact('day_stats', 'week_stats', 'month_stats', 'data'));
 }

效果图:

以上这篇Laravel统计一段时间间隔的数据方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持黑区网络。