فرض کنید می خواهید نتایج جدول را بر اساس تاریخ ایجاد (created_at) فیلتر کنید. خوب شما چطور این کارو می کنید ؟
بعضی از مردم از کوئری های خام استفاده می کنند.مثل این:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
یا بدون کوئری خام :
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
خوشبختانه Query Builder لاراول متدهای بیشتری در این زمینه دارد:
$q->whereDate('created_at', '=', date('Y-m-d'));
البته به جای تابع Date در PHP، می توانید از Carbon استفاده کنید:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
یا در بعضی از پروژه ها نیاز به گرفتن آمار فروش در بازه های زمانی مختلف مثل “۱ ساعت قبل”، “۱ روز قبل”، “۱ ماه قبل” و …. پیدا کردم که با روش زیر به راحتی می تونید این کارو انجام بدید:
$lastHour = Carbon::now()->subHour(1); $lastDay = Carbon::now()->subDay(1); $lastWeek = Carbon::now()->subWeek(1); $lastMonth = Carbon::now()->subMonth(1); $lastYear = Carbon::now()->subYear(1); return [ 'reservation_last_hour' => Reservation::where('created_at','>', $lastHour)->count(), 'reservation_last_day' => Reservation::where('created_at','>', $lastDay)->count(), 'reservation_last_week' => Reservation::where('created_at','>', $lastWeek)->count(), 'reservation_last_month' => Reservation::where('created_at','>', $lastMonth)->count(), 'reservation_last_year' => Reservation::where('created_at','>', $lastYear)->count(), ];
Reservation دقیقا چیکار میکنه؟
منظور مدل Reservation هست . برای کار با دیتابیس