PHP Carbon / Laravel Eloquent - 检查 DateTime 值是否为当天

PHP Carbon / Laravel Eloquent - Check if DateTime value is for the current day

我正在开发一个预订系统,需要 select 仅记录今天某个字段的记录。不是今天,也不是未来,只有今天。

当前查询是:

$advancedBookings = Booking::where('type', 2)
    ->whereNull('estimated_booking_time')
    ->where('requested_booking_time', ?????);

$advancedBookings->get();

requested_booking_time是我要检查的字段,存储的日期是这样的格式:

2017-08-23 08:00:00

所以我只想 select 与当天同一天的行。

你应该试试这个:

$advancedBookings = Booking::where('type', 2)
    ->whereNull('estimated_booking_time')
    ->whereDate('requested_booking_time', '=', date('Y-m-d'))
    ->get();

据我了解,您想要今天创建的记录;然后获取今天的日期。

$today = date("Y-m-d");

现在你的查询是这样的。

$advancedBookings = Booking::where('type', 2)
    ->whereNull('estimated_booking_time')
    ->where('requested_booking_time', $today)->get();

您可以使用 whereDate 并将您的日期格式化为 Carbon:

$advancedBookings = Booking::where('type', 2)
    ->whereNull('estimated_booking_time')
    ->whereDate('requested_booking_time', '=' , Carbon::today()->toDateString());

$advancedBookings->get();

或者在查询前用 Carbon 格式化您的日期。