yii:如何为两个属性制定唯一规则 [英] yii: how to make a unique rule for two attributes

查看:85
本文介绍了yii:如何为两个属性制定唯一规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表: (ID,名称,版本,文本). (名称,版本)是唯一密钥,我如何制定规则对此进行验证.

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

推荐答案

这可以由Yii本身完成,您不需要扩展. 但是,扩展名可以帮助清理rules()方法,如下所述:

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
            )
        )),
    );
}

如果$this->secondKey的值在rules()方法中不可用,则可以在CActiveRecords beforeValidate()方法中添加验证器,如下所示:

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;
}

这篇关于yii:如何为两个属性制定唯一规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆