从数据库中获取所有记录到 Laravel 中的特定月份
Getting all records from data base to a specific month in 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();
}
但我总是得到 null!!
假设您在数据库中对这些日期进行了预订,请尝试让 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();
在我的数据库中我有这个预订记录
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();
}
但我总是得到 null!!
假设您在数据库中对这些日期进行了预订,请尝试让 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();