yii: how to make a unique rule for two attributes

后端 未结 8 546
一生所求
一生所求 2020-12-29 02:26

I have a table like this: (id, name, version, text). (name, version) is unique key, how can i make a rule to validate this.

8条回答
  •  遥遥无期
    2020-12-29 02:51

    You do not need complicated content of rules() method nor 3rd party extensions. Just create your own validation method. It's much easier to do it on your own.

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

提交回复
热议问题