yii: how to make a unique rule for two attributes

后端 未结 8 565
一生所求
一生所求 2020-12-29 02:26

I have a table like this: (id, name, version, text). (name, version) is unique key, how can i make a rule to validate this.

8条回答
  •  心在旅途
    2020-12-29 03:05

    They've added support for unique composite keys in the next release candidate of Yii1.14rc, but here's (yet another) solution. BTW, this code uses the same 'attributeName' in the rules that the Yii framework will use in the next official release.

    protected/models/Mymodel.php

        public function rules()
        {
            return array(
                array('name', 'uniqueValidator','attributeName'=>array(
                  'name', 'phone_number','email') 
            ),
    ...
    
    • 'name' in the beginning of the rule is the attribute the validation error will be attached to and later output on your form.
    • 'attributeName' (array) contains an array of keys that you would like to validate together as a combined key.

    protected/components/validators/uniqueValidator.php

      class uniqueValidator extends CValidator
        {
            public $attributeName;
            public $quiet = false; //future bool for quiet validation error -->not complete
        /**
         * Validates the attribute of the object.
         * If there is any error, the error message is added to the object.
         * @param CModel $object the object being validated
         * @param string $attribute the attribute being validated
         */
        protected function validateAttribute($object,$attribute)
        {
            // build criteria from attribute(s) using Yii CDbCriteria
            $criteria=new CDbCriteria();
            foreach ( $this->attributeName as $name )
                $criteria->addSearchCondition( $name, $object->$name, false  );
    
            // use exists with $criteria to check if the supplied keys combined are unique
            if ( $object->exists( $criteria ) ) {
                $this->addError($object,$attribute, $object->label() .' ' .
                  $attribute .' "'. $object->$attribute . '" has already been taken.');
            }
        }
    
    }
    

    You can use as many attributes as you like and this will work for all of your CModels. The check is done with "exists".

    protected/config/main.php

    'application.components.validators.*',
    

    You may have to add the above line to your config in the 'import' array so that uniqueValidator.php will be found by the Yii application.

    Positive feedback and changes are very welcome!

提交回复
热议问题