yii:如何为两个属性制定唯一规则

li *_*ong 34 yii yii-validation yii1.x

我有一个这样的表:(id,name,version,text).(名称,版本)是唯一键,我如何制定规则来验证这一点.

ceb*_*ebe 52

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

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

这是在不使用扩展名的情况下可以使用的代码(从该站点复制):

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

如果$this->secondKeyrules()-method中没有值,则可以在CActiveRecords beforeValidate()-method中添加验证器,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)


Rac*_*cky 8

您不需要复杂的rules()方法内容或第三方扩展.只需创建自己的验证方法.自己做这件事要容易得多.

public function rules()
{
  return array(
    array('firstField', 'myTestUniqueMethod'),
  );
}

public function myTestUniqueMethod($attribute,$params)
{

   //... and here your own pure SQL or ActiveRecord test ..
   // usage: 
   // $this->firstField;
   // $this->secondField;
   // SELECT * FROM myTable WHERE firstField = $this->firstField AND secondField = $this->secondField ...
   // If result not empty ... error

  if (!$isUnique)
  {
    $this->addError('firstField', "Text of error");
    $this->addError('secondField', "Text of error");
  }

}
Run Code Online (Sandbox Code Playgroud)


sj5*_*j59 6

Yii1:

http://www.yiiframework.com/extension/composite-unique-key-validatable/

Yii2:

// a1 needs to be unique
['a1', 'unique']
// a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2']
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]
Run Code Online (Sandbox Code Playgroud)

http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html


Jes*_*e C 5

他们在 Yii1.14rc 的下一个候选版本中添加了对独特复合键的支持,但这是(又一个)解决方案。顺便说一句,此代码在 Yii 框架将在下一个正式版本中使用的规则中使用相同的“attributeName”。

受保护/模型/Mymodel.php

    public function rules()
    {
        return array(
            array('name', 'uniqueValidator','attributeName'=>array(
              'name', 'phone_number','email') 
        ),
...
Run Code Online (Sandbox Code Playgroud)
  • 规则开头的“名称”是将验证错误附加到的属性,并稍后输出到表单上。
  • “attributeName”(数组)包含您希望作为组合键一起验证的键数组。

受保护/组件/验证器/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.');
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

您可以使用任意数量的属性,这将适用于您的所有 CModel。检查是通过“存在”完成的。

受保护/配置/main.php

'application.components.validators.*',
Run Code Online (Sandbox Code Playgroud)

您可能需要将以上行添加到“导入”数组中的配置中,以便 Yii 应用程序找到 uniqueValidator.php。

非常欢迎积极的反馈和改变!


Ant*_*ška 5

在Yii2中:

public function rules() {
    return [
        [['name'], 'unique', 'targetAttribute' => ['name', 'version']],
    ];
}
Run Code Online (Sandbox Code Playgroud)