日期检查方法update()

时间:2019-09-13 20:35:34

标签: laravel laravel-5

我的函数store()有效,但是我不知道如何在方法update()中进行调整?

$conflictTraining = Training::where('fk_motorbike', $request->get('fk_motorbike'))
        ->whereDate('date_seance', "=" , $date_revision_start)
        ->where('hour_start', "<=" , $request->get('hour_start')) 
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->first();

$conflictTraining2 = Training::where('fk_motorbike', $request->get('fk_motorbike'))
        ->whereDate('date_seance', "=" , $date_revision_end)
        ->where('hour_start', "<=" , $request->get('hour_start')) 
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->first();

这是我的函数update()的一个主意,但这并不好...

$conflictTraining = Training::where('id', '!=', $id)
        ->where('fk_motorbike', $request->get('fk_motorbike'))
        ->whereDate('date_seance', "=" , $date_revision_start)
        ->where('hour_start', "<=" , $request->get('hour_start')) 
        ->first();

        $conflictTraining2 = Training::where('fk_motorbike', $request->get('fk_motorbike'))
        ->whereDate('date_seance', "=" , $date_revision_end)
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->first();

if( (isset($conflictTraining2) && $conflictTraining2->id !== intval($id))
        || (isset($conflictTraining) && $conflictTraining->id !== intval($id)) ){
            return redirect()->route('revisions.index')
             ->with('error', 'date duplicate ');
        }

1 个答案:

答案 0 :(得分:1)

尝试解决时间交集时确实遇到了类似的问题,我使用datetime而不是仅使用时间来存储时间间隔。

为解决这个问题,创建了两种方法,一种检查内部期间冲突,另一种检查外部期间冲突。

首先,我建议您将字段start_hourend_hour分别更改为start_timeend_time,这两种日期时间类型都是

使用这些方法在此处获取模型样本

class Training extends Model
{
    protected $fillable = [
        'start_time',
        'end_time'
    ];

    public function isValidOrFail()
    {
        $collection = $this->all();

        $collection->each(function ($current)  {
            if($current->start_time and  $current->end_time) {
                if($this->hasConflictWithInternalPeriod($current) or $this->hasConflictWithExternalPeriod($current)) {
                    throw new InvalidPeriodException("Here my exception message");
                }
            }
        });

        return true;
    }

    protected function hasConflictWithInternalPeriod($training)
    {
        return $this->start_time->between($training->start_time, $training->end_time)
            or $this->end_time->between($training->start_time, $training->end_time);
    }

    protected function hasConflictWithExternalPeriod($training)
    {
        return $training->start_time->between($this->start_time, $this->end_time
            or $training->end_time->between($this->start_time, $this->end_time);
    }
}

这听起来可能与您的期望有很大不同,但我希望它能对您有所帮助。

您调用方法isValidOrFail(),它将针对所有其他记录检查当前模型,从而验证内部和外部期间冲突。