如果用户请求的 DateTime 与 MYSQL 数据库中已有的任何 DateTime 重叠,我一直在努力使用返回 true
或 false
的函数。
情况是用户可以通过 iOS 应用程序提交租车请求,它采用 DateTime 格式 2014-04-02 08:49:43
。我使用 Laravel 作为 API 来管理后端。 Reservation
的表是:
Schema::table('reservations', function($table)
{
$table->dateTime('from_date')->nullable();
$table->dateTime('to_date')->nullable();
});
所以我尝试了很多方法,但在过去的 2 天里,保留日期和时间而不重叠一直很痛苦。我最接近的是这个功能,我认为(希望)这个功能是正确的,但缺少一些东西。
public function isSlotAvailable(Request $request) {
$appointments = Reservation::all();
$from = $request->from;
$to = $request->to;
foreach ($appointments as $appointment) {
$eventStart = Carbon::instance(
new DateTime($appointment['dt_start'])
);
$eventEnd = Carbon::instance(
new DateTime($appointment['dt_end'])
)->subSecond(1);
if ($from->between($eventStart, $eventEnd) ||
$to->between($eventStart, $eventEnd) ||
($eventStart->between($from, $to) && $eventEnd->between($from, $to)))
{
return false;
}
}
return true;
}
我从这个函数得到的错误是:
Call to a member function between() on string
如果有任何帮助,我将不胜感激。
最佳答案
与其尝试使用 between(),不如检查一下
if($from<$eventEnd && $to>$eventStart){
return false;
}
除了您的新事件在现有事件开始之前开始和结束,或者您的新事件在现有事件之后开始和结束的情况外,所有情况都应返回 false。
这假设您已经检查了 $from<$to
和 $eventStart<$eventEnd
在所有情况下,我希望是这样!
关于php - 返回给定时间/日期的可用性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434215/