在我的数据库里我有这个预订记录
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();
}
但我总是变得空!!
假设您在数据库中保留了这些日期,请尝试让 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();
强制格式化
Carbon
$reservations = $restaurant
->reservations()
->where('confirme',2)
->whereBetween('reservation_date',[
$today->startOfMonth()->format('Y-m-d'),
$today->endOfMonth()->format('Y-m-d')
])->get();
您还可以使用 whereMonth 以及类似的 whereYear
$month = 1; // january
$reservations->whereMonth('created_at', $month)
$year = 2022;
$reservations->whereYear('created_at', $year)