yii:如何为两个属性创建唯一的规则

zynd9foi  于 2022-11-09  发布在  其他
关注(0)|答案(8)|浏览(164)

我有这样一张表:(ID,名称,版本,文本)。(名称,版本)是唯一的关键字,我如何制定一个规则来验证这一点。

vfhzx4xs

vfhzx4xs1#

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

cygmwpex2#

你不需要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");
  }

}
l0oc07j2

l0oc07j23#

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

2eafrhcq

2eafrhcq4#

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

保护的/模型/我的模型.php

public function rules()
    {
        return array(
            array('name', 'uniqueValidator','attributeName'=>array(
              'name', 'phone_number','email') 
        ),
...
  • 规则开头的'name'是验证错误将附加到的属性,稍后会输出到表单上。
  • 'attributeName'(array)包含您要一起验证为组合键的键数组。
    受保护的/组件/验证器/唯一验证器.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都有效。检查是用“exists”来完成的。

保护/配置/主.php

'application.components.validators.*',

您可能需要将上面的行添加到'import'数组中的config中,这样uniqueValidator.php才能被Yii应用程序找到。
积极的反馈和变化是非常欢迎的!

mw3dktmi

mw3dktmi5#

在Yii2中:

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

sg3maiej6#

基于上面的函数,下面是一个可以添加到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;
}
sq1bmfud

sq1bmfud7#

这很简单,在数组中包含一个在扩展类中创建的参数。
下一个代码在Model中。

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

z9zf31ra8#

也许你可以把这个rules添加到你的代码中

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

相关问题