首页 > 解决方案 > 在 Laravel 中获取数据库中的所有记录到特定月份

问题描述

在我的数据库中,我有这个预订记录

App\Reservation {#2632
     id: 1,
     user_id: 7,
     rest_id: 23,
     reservation_date: "2019-08-29",
     from_time: "16:00:00",
     to_time: "00:00:00",
     count_of_people: 15,
     loyalty_points: 100,
     confirme: 2,
     cancle: 0,
     surveySended: 0,
     surveyAnswer: 0,
     created_at: null,
     updated_at: null,
   },

在我的控制器中,我有这段代码试图检索本月的所有预订:

public function getRestAdmin(Request $request,$rest_id)
{

$restaurant=Restaurant::find($rest_id);
  $today=\Carbon\Carbon::today();
//reservations made this month
$reservations=$restaurant->reservations()->where('confirme',2)->whereBetween('reservation_date',[$today->startOfMonth(),$today->endOfMonth()])->get();
 }

但我总是无效!

标签: laraveleloquentphp-carbon

解决方案


假设您在数据库中有这些日期的预订,请尝试让 Carbon 在直接查询之前完成繁重的工作(无需先设置为今天):

$start = new Carbon('first day of this month');
$end = new Carbon('last day of this month');

然后只需将变量添加到查询中:

whereBetween('reservation_date',[$start, $end]) ...

您也可以在 Carbon 上使用此方法:

$start = Carbon::now()->startOfMonth();

推荐阅读