如何在Laravel中按时间明智地验证名称

在我的项目中,可能会有多个班次,称为“ day”。现在,我想验证一下这次,以便与此同时没有时间冲突。或简单地说,不能同时或在两个时间之间存在两个转变。

我尝试过以下操作,但这不起作用:

$shifts = Shift::where('name',$request->name)
            ->whereTime('in_time','>=',$request->in_time)
            ->WhereTime('out_time','<=',$request->out_time)
            ->pluck('name');
            'name' => [
            'required',Rule::unique('shifts','name')->where(function ($query) use ($shifts){
                return $query->whereIn('name',$shifts);
            })
        ],
oyangnann 回答:如何在Laravel中按时间明智地验证名称

用于查找重叠时间的查询应该是固定的:

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

大家都在问