Как проверить имя по времени в laravel - PullRequest
1 голос
/ 06 ноября 2019

В моем проекте может быть несколько смен, называемых днем. Теперь я хочу проверить это время, чтобы между тем не было никакого конфликта времени. Или, простым словом, не может быть двух сдвигов одновременно или между этими временами.

Я пробовал, как следующее, но это не работает:

$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);
            })
        ],

1 Ответ

2 голосов
/ 06 ноября 2019

Запрос на поиск перекрывающихся времен должен быть исправлен:

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"
    ]);
}

Это длиннее, но безопаснее, и ясно показывает, что выпытаясь достичь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...