3

in Yii framework, can I use unique validation rule to check uniqueness of an field within some condition (I know there is criteria, but this condition is a bit tricky)? Ie, i want to check num_days unique by property_id.

table:

NUM PROP_ID

3   4

3   5

validation should pass in case i try insert 3, 6, but fail in case of 3, 4

hakre
  • 193,403
  • 52
  • 435
  • 836
dzona
  • 3,323
  • 3
  • 31
  • 47

3 Answers3

3

Check out UniqueAttributesValidator, and also this answer. In the links you'll see that they have used $this->attributename for the params array of the criteria option of CUniqueValidator, but for some reason $this->attributename was null for me. I believe that this is because the $this is not being passed correctly to the validator, so anyway it would be best to use the UniqueAttributesValidator class, because it has been made just for these kinds of situations.

The resulting sql will have a WHERE clause like this:

SELECT ... WHERE (`num`=:value) AND (`prop_id`=:prop_id) ...

which will easily fail for 3, 4 and pass for 3, 6. So it should work for your situation.

Community
  • 1
  • 1
bool.dev
  • 17,508
  • 5
  • 69
  • 93
2

First Create unique field in you table

and in model add this to your rules()

 array('field_name', 'unique'),

For combination of two fields unique use this code

public function rules() {
return array(
    array('firstKey', 'unique', 'criteria'=>array(
        'condition'=>'`secondKey`=:secondKey',
        'params'=>array(
            ':secondKey'=>$this->secondKey
        )
    )),
);
}
nitin
  • 89
  • 10
1

Create your custom Validator or validation function, it's simple.