yii:如何为两个属性制定唯一规则 [英] yii: how to make a unique rule for two attributes
问题描述
我有一个这样的表: (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屋!