34

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

4

8 回答 8

53

这可以由 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在 -method 中不可用,rules()您可以在 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;
}
于 2012-03-13T21:43:23.467 回答
9

您不需要 rules() 方法的复杂内容,也不需要 3rd 方扩展。只需创建自己的验证方法。自己做会容易得多。

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

}
于 2014-03-25T10:06:03.320 回答
7

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

于 2015-12-03T07:41:29.480 回答
5

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

受保护的/模型/Mymodel.php

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

protected/components/validators/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。检查是用“存在”完成的。

保护/配置/main.php

'application.components.validators.*',

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

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

于 2014-03-31T20:13:06.113 回答
5

在 Yii2 中:

public function rules() {
    return [
        [['name'], 'unique', 'targetAttribute' => ['name', 'version']],
    ];
}
于 2016-02-11T15:03:34.657 回答
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;
}
于 2017-05-23T14:45:31.990 回答
-2

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

下一个代码在模型内部。

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

下一个代码是从类ValidateNames到扩展文件夹。

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);
    }
}
于 2014-05-13T20:39:57.970 回答
-5

也许您可以将其添加rules到您的代码中

return array(
    array('name', 'unique', 'className'=>'MyModel', 'attributeName'=>'myName'),
    array('version', 'unique', 'className'=>'MyModel', 'attributeName'=>'myVersion')
);
于 2012-03-12T17:55:26.740 回答