如何在 PHP Laravel 中檢查時間段是否與另一個時間段重疊
P粉011360903
2023-09-03 00:18:11
<p>如何檢查資料庫中是否已存在給定時間段內特定使用者的工作時間。因此,當工作時間與給定日期和時間重疊時,函數應傳回 true。我試過了,但這不起作用。 </p>
<pre class="brush:php;toolbar:false;">function checkExistingWorkingHours($user_id, $start_date, $start_time, $end_date, $end_time)
{
// dd($user_id . " " . $start_date . " " . $start_time . " " . $end_date . " " . $end_time);
$startDateTime = Carbon::parse($start_date . ' ' . $start_time);
$endDateTime = Carbon::parse($end_date . ' ' . $end_time);
$overlapExists = WorkingHour::where('user_id', $user_id)
->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where(function ($query) use ($startDateTime, $endDateTime) {
// Check for overlap where the start_datetime is between existing start_datetime and end_datetime
$query->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '=', $startDateTime->format('Y-m-d'))
->where('start_time', '<', $endDateTime->format('H:i'))
->where('end_date', '=', $startDateTime->format('Y-m-d'))
->where('end_time', '>', $startDateTime->format('H:i'));
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '<', $startDateTime->format('Y-m-d'))
->where('end_date', '=', $startDateTime->format('Y-m-d'))
->where('end_time', '>', $startDateTime->format('H:i'));
});
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
// Check for overlap where the end_datetime is between existing start_datetime and end_datetime
$query->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '=', $endDateTime->format('Y-m-d'))
->where('end_date', '>=', $endDateTime->format('Y-m-d'))
->where('start_time', '<', $endDateTime->format('H:i'));
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '<=', $startDateTime->format('Y-m-d'))
->where('end_date', '>=', $endDateTime->format('Y-m-d'));
});
});
})->exists();
return $overlapExists;
}</pre>
<p>當我使用以下資料測試函數時,它說存在重疊,即使沒有重疊。 </p>
<p>檢查現有工作時間(1, 2023-06-01, 00:15, 2023-06-01, 03:00);</p>
<p>資料庫中的值是 2023-06-01 03:30 到 11pm。 </p>
嘗試使用這個
根據geertjanknapen的評論回答: