这是我的表event
如你所见
交易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))
是错误的。
但我不知道怎么写条件来检查那件事。
答案 0 :(得分:0)
这有用吗:
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']
的规则。