问题
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
回答1:
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.
回答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
)
)),
);
}
回答3:
Create your custom Validator or validation function, it's simple.
来源:https://stackoverflow.com/questions/10432591/yii-validation-rule-unique