Yii2如何在模型中使用activequery作为唯一验证器

时间:2017-04-04 10:02:12

标签: validation yii2 unique

如何在模型中使用activequery作为唯一验证器

  ['amenityName', 'unique', 'targetClass' => Amenity::className(), 'message' => 'This amenity has already been taken.',
                 'when' => function ($model, $attribute) {
                   return $model->{$attribute} !== $model->getOldAttribute($attribute);
               },],

在activequery中

public function active()
{  
        return $this->andWhere(['amenityStatus' => '1']);
} 

    /**
     * @inheritdoc
     * @return Amenity[]|array
     */
    public function all($db = null)
    {
        return parent::all($db);
    }

我想获得数据有效的amenityname的唯一值。现在我从所有不活跃的数据中检查

1 个答案:

答案 0 :(得分:2)

你可以直接使用独特的验证器......例如在Amenity Model中:

 public function rules()
    {
        return [
               // a1 needs to be unique in the column represented by the "a1" attribute
              ['amenityName', 'unique'],
              ....

您可以在此处获得有关唯一验证器功能的更多信息http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#unique
http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html