我如何将其转换为:
public function rules() {
return [
[['attr1', 'attr2'], 'unique', 'skipOnEmpty' => false, 'skipOnError' => false, targetAttribute' => ['attr1', 'attr2']],进入内联验证器,或者作为内联验证器的等效性是什么?谢谢。
发布于 2020-09-17 18:48:47
不可能像https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation中所解释的那样,将唯一验证器作为临时使用。
Note: Not all validators support this type of validation. An example is the unique core validator which is designed to work with a model only.
你必须自己建造它。
其他方法可以是将查询包装到try catch中,前提是数据库上有一个唯一的键。数据库将抱怨查询,您可以捕获错误。
为内联验证编辑:
这是一个非常具体的验证器,您将不会重用它,因此,让我们将它内联为一个匿名函数:
public function rules(){
[['attr1'], function(){
//we know the names of the attribute so we use them here directly instead of pass as a parameter
if(self::find()->where([
'attr1' => $this->attr1,
'attr2' => $this->attr2
])->exists()){
$this->addError('attr1', 'Error message');
$this->addError('attr2', 'Error message');
}
}]
}注意,我刚刚为attr1注册了验证。如果还注册了attr2,那么每个属性都会出现两个错误。
https://stackoverflow.com/questions/63936854
复制相似问题