阅读目录 
 
 
 
场景 
- 场景
因项目中用到了图表之类的信息,需要获取到很多时间的数据动态,刚开始我都是自己换算时间来计算,后来 看到手册中有更简单的方法,自己总结了一下通用的时间段统计(今天、昨天、上周、本周、上月、本月、上年、本年)。
use Carbon\Carbon;
 
public function getNumber()
{
  $data = [];
  #今天数据
  $data['customer_today'] = Customer::where('customer_type', 1)->where('created_at', Carbon::today())->count();
  #昨天数据
  $data['customer_yesterday'] = Customer::where('customer_type', 1)->where('created_at', Carbon::yesterday())->count();
  // 本周数据
  $this_week = [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()];
  $data['customer_this_week'] = Customer::where('customer_type', 1)->whereBetween('created_at', $this_week)->count();
  // 上周数据
  $last_week = [Carbon::now()->startOfWeek()->subWeek(), Carbon::now()->endOfWeek()->subWeek()];
  $data['customer_last_week'] = Customer::where('customer_type', 1)->whereBetween('created_at', $last_week)->count();
  // 本月数据
  $data['customer_this_month'] = Customer::where('customer_type', 1)->whereMonth('created_at', Carbon::now()->month)->count();
  // 上月数据
  $data['customer_last_month'] = Customer::where('customer_type', 1)->whereMonth('created_at', Carbon::now()->subMonth()->month)->count();
  // 本年数据
  $data['customer_this_year'] = Customer::where('customer_type', 1)->whereYear('created_at', Carbon::now()->year)->count();
 
  return $data;
}

 
                 
    