用于查找重叠时间的查询应该是固定的:
Shift::where( function ($query) use ($request) {
# New shift `in_time` is included in another shift
# i.e. Another shift has not finished yet when this one beings
$query->where('in_time','<',$request->in_time )
->where('out_time','>',$request->in_time );
})
->orWhere( function ($query) use ($request) {
# New shift `out_time` is included in another shift
# i.e. Another shift starts before this one begins
$query->where('in_time',$request->out_time )
->where('out_time',$request->out_time );
});
将它们放在一起:
# Make sure the input is in the right format before using it in a query:
$rules = [
'in_time' => 'required|date_format:H:i','out_time' => 'required|date_format:H:i','name' => 'required|string|max:100'
];
$request->validate($rules);
# Now check that times aren't overlapping. Just check if a clashing entry exists in the database:
$clash = Shift::where('name',$request->name)
->where( function ($query) use ($request) {
$query->where( function ($query) use ($request) {
$query->where('in_time',$request->in_time )
->where('out_time',$request->in_time );
})->orWhere( function ($query) use ($request) {
$query->where('in_time',$request->out_time )
->where('out_time',$request->out_time );
});
})->exists();
# If a clash exists,throw a validation error
if ( $clash ) {
throw ValidationException::withMessages([
'name' => "There's an overlapping shift with that name"
]);
}
更长,但是更安全,并且清楚地表明了您要实现的目标。
本文链接:https://www.f2er.com/3154146.html