yii: how to make a unique rule for two attributes

后端 未结 8 483
一生所求
一生所求 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:01

    This can be done by Yii itself, you do not need an extension for it. However an extension can help cleaning up the rules() method as described here:

    http://www.yiiframework.com/extension/unique-attributes-validator/

    This is the code (copied from that site) which will work without using the extension:

    public function rules() {
        return array(
            array('firstKey', 'unique', 'criteria'=>array(
                'condition'=>'`secondKey`=:secondKey',
                'params'=>array(
                    ':secondKey'=>$this->secondKey
                )
            )),
        );
    }
    

    In case the value of $this->secondKey is not available inside rules()-method you can add the validator in CActiveRecords beforeValidate()-method like this:

    public function beforeValidate()
    {
        if (parent::beforeValidate()) {
    
            $validator = CValidator::createValidator('unique', $this, 'firstKey', array(
                'criteria' => array(
                    'condition'=>'`secondKey`=:secondKey',
                    'params'=>array(
                        ':secondKey'=>$this->secondKey
                    )
                )
            ));
            $this->getValidatorList()->insertAt(0, $validator); 
    
            return true;
        }
        return false;
    }
    

提交回复
热议问题