Yii2 验证规则:如何检查日期时间和地点不与另一个条目冲突?

Yii2 Validation rule: How to check datetime and place does not collidate with another entry?

这是我的tableevent

如你所见

交易 1

time_begin: 2016-03-10 07:00:00    
time_end:   2016-03-10 08:00:00  
place:      1

如果用户进行交易 2 然后选择

time_begin: 2016-03-10 07:15:00     
time_end:   2016-03-10 07:45:00 
place:      1

如何制定自定义验证规则来检查日期时间和地点是否未在另一笔交易中使用?

所以我试过了:

// models.php

public function rules()
{
    return [
        [['title', 'description', 'time_begin', 'time_end', 'place'], 'required'],
        [['description', 'status'], 'string'],
        [['time_begin', 'time_end'], 'safe'],
        [['title'], 'string', 'max' => 150],
        [['place'], 'string', 'max' => 50],
        [['remark'], 'string', 'max' => 145],
        [['time_end'], 'compare','compareAttribute'=>'time_begin','operator'=>'>','message'=>''],
        [['place', 'time_begin'], 'unique', 'targetAttribute' => ['place', 'time_begin'],'message'=>'time and place is busy place select new one.'],
        [['place'], 'checkDate','skipOnEmpty' => false],
    ];
}


public function checkDate($attribute, $params)
{
    $a = Event::find()->where(['>=', 'time_begin', ($this->time_begin)])->count();
    $b = Event::find()->where(['<=', 'time_end', ($this->time_end)])->count();
    $c = Event::find()->where(['=', 'place', ($this->place)])->count();
    $d = ($this->time_begin);
    $e = ($this->time_end);
    $f = ($this->place);
    if (($d > $a) && ($f = $c))
    {
         $this->addError($attribute, 'This place and time is busy, selcet new place or change time.');
    }
}

它不会工作,因为这个 if (($d > $a) && ($f = $c)) 是错误的。

但是我不知道怎么写检查那个东西的条件

这有帮助吗:

public function checkDate($attribute, $params)
{
    $thereIsAnOverlapping = Event::find()->where(
        ['AND',
            ['place' => $this->place],
            ['<=', 'time_begin', $this->time_end],
            ['>=', 'time_end', $this->time_begin]
        ])->exists();

    if ($thereIsAnOverlapping) {
         $this->addError($attribute, 'This place and time is busy, selcet new place or change time.');
    }
}

这会检查是否有另一个事件具有相同的房间并且时间重叠(完全或部分)。

有了这个我想你可以省略 ['place', 'time_begin'] 的规则。