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

时间:2012-03-12 16:30:32

标签: yii yii-validation

我有这样一张桌子: (id,name,version,text)。 (名称,版本)是唯一键,我如何制定规则来验证这一点。

8 个答案:

答案 0 :(得分:50)

这可以由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
            )
        )),
    );
}

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

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

答案 1 :(得分: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");
  }

}

答案 2 :(得分:5)

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']]

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

答案 3 :(得分:4)

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

<强>保护/模型/ Mymodel.php

    public function rules()
    {
        return array(
            array('name', 'uniqueValidator','attributeName'=>array(
              'name', 'phone_number','email') 
        ),
...
  • &#39;名称&#39;在规则的开头是验证错误将附加到以后在表单上输出的属性。
  • &#39;的attributeName&#39; (array)包含一组键,您希望将它们作为组合键一起验证。

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

}

您可以使用任意数量的属性,这将适用于您的所有CModel。检查是通过&#34; exists&#34;完成的。

<强>保护/配置/ main.php

'application.components.validators.*',

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

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

答案 4 :(得分:4)

在Yii2:

public function rules() {
    return [
        [['name'], 'unique', 'targetAttribute' => ['name', 'version']],
    ];
}

答案 5 :(得分:0)

基于上述功能,这里有一个可以添加到ActiveRecord模型

的功能

你会像这样使用它,

array( array('productname,productversion'), 'ValidateUniqueColumns', 'Product already contains that version'),


/*
 * Validates the uniqueness of the attributes, multiple attributes
 */
public function ValidateUniqueColumns($attributes, $params)
{
    $columns = explode(",", $attributes);
    //Create the SQL Statement
    $select_criteria = "";
    $column_count = count($columns);
    $lastcolumn = "";

    for($index=0; $index<$column_count; $index++)
    {
        $lastcolumn = $columns[$index];
        $value = Yii::app()->db->quoteValue( $this->getAttribute($columns[$index]) );
        $column_equals = "`".$columns[$index]."` = ".$value."";
        $select_criteria = $select_criteria.$column_equals;
        $select_criteria = $select_criteria."  ";
        if($index + 1 < $column_count)
        {
            $select_criteria = $select_criteria." AND ";
        }
    }

    $select_criteria = $select_criteria." AND `".$this->getTableSchema()->primaryKey."` <> ".Yii::app()->db->quoteValue($this->getAttribute( $this->getTableSchema()->primaryKey ))."";

    $SQL = " SELECT COUNT(`".$this->getTableSchema()->primaryKey."`) AS COUNT_ FROM `".$this->tableName()."` WHERE ".$select_criteria;

    $list = Yii::app()->db->createCommand($SQL)->queryAll();
    $total = intval( $list[0]["COUNT_"] );

    if($total > 0)
    {
        $this->addError($lastcolumn, $params[0]);
        return false;
    }

    return true;
}

答案 6 :(得分:-2)

这很容易。在您的数组中,包含在扩展类中创建的参数。

下一个代码在Model中。

array('name', 'ext.ValidateNames', 'with'=>'lastname')

下一个代码从类ValidateNames进入extensions文件夹。

class ValidateNames extends CValidator
{
    public $with=""; /*my parameter*/

    public function validateAttribute($object, $attribute)
    {
        $temp = $this->with;  
        $lastname = $object->$temp;
        $name = $object->$attribute;
        $this->addError($object,$attribute, $usuario." hola ".$lastname);
    }
}

答案 7 :(得分:-5)

您可以将此rules添加到您的代码中

return array(
    array('name', 'unique', 'className'=>'MyModel', 'attributeName'=>'myName'),
    array('version', 'unique', 'className'=>'MyModel', 'attributeName'=>'myVersion')
);