34

次のようなテーブルがあります: (id、名前、バージョン、テキスト)。(名前、バージョン) は一意のキーです。これを検証するルールを作成するにはどうすればよいですか。

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

の値が-method$this->secondKey内で使用できない場合は、次のようrules()にCActiveRecords-methodにバリデーターを追加できます。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;
}
于 2012-03-13T21:43:23.467 に答える
9

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

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

Yii2 では:

public function rules() {
    return [
        [['name'], 'unique', 'targetAttribute' => ['name', 'version']],
    ];
}
于 2016-02-11T15:03:34.657 に答える
5

彼らは、Yii1.14rc の次のリリース候補で一意の複合キーのサポートを追加しましたが、ここに (さらに別の) 解決策があります。ところで、このコードは、Yii フレームワークが次の公式リリースで使用するルールで同じ 'attributeName' を使用します。

保護された/モデル/Mymodel.php

    public function rules()
    {
        return array(
            array('name', 'uniqueValidator','attributeName'=>array(
              'name', 'phone_number','email') 
        ),
...
  • ルールの先頭にある「名前」は、検証エラーが添付され、後でフォームに出力される属性です。
  • '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.');
        }
    }

}

好きなだけ属性を使用でき、これはすべての CModel で機能します。チェックは「存在する」で行われます。

保護された/config/main.php

'application.components.validators.*',

Yii アプリケーションが uniqueValidator.php を見つけられるように、上記の行を構成の「import」配列に追加する必要がある場合があります。

正のフィードバックと変更は大歓迎です!

于 2014-03-31T20:13:06.113 に答える
-2

それは非常に簡単です。配列に、拡張機能クラスで作成されたパラメーターを含めます。

次のコードはモデル内にあります。

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

次のコードは、クラスからValidateNamesextensions フォルダーに移動します。

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 に答える