CakePHP unique compound field validation (not unique each field, but as a whole)

StackOverflow https://stackoverflow.com/questions/22767389

  •  24-06-2023
  •  | 
  •  

Pregunta

So I need to validate if both fields are the same, not each field on its own. By that I mean:

id (auto increment)  |  field_1  | field_2
------------------------------------------
          1          |    1      |    1

if I try to insert null,1,1 it will show error. But if I go null,1,2 it inserts it with no problem.

In conclusion, the whole (field_1, field_2) is what's is unique (also know as compound primary key).

how can I validate this in Model?

EDIT: I tried this: Validation rule for a composite unique index (non-primary), but it validates each field on it's own, so if I go null,1,2 it won't insert, cause field_1 = 1 already exists in the table

¿Fue útil?

Solución 2

Try this custom validation function on Model.

public function compositUniqueKey($data){

if(isset($this->data[$this->alias]['field1']) && isset($this->data[$this->alias]['field1']) ){  
    $check = $this->find('first', array(
                                        'conditions' => array(
                                            'field1' => $this->data[$this->alias]['field1'],
                                            'field2' => $this->data[$this->alias]['field2']
                                        )
                                    )
                                );
    if(!empty($check)){
        return false;
    }
    return true;

}else{
    return false;
}

}

Otros consejos

Model::isUnique() is a rule that can be used and is already implemented in the CakePHP core.

Returns false if any fields passed match any (by default, all if $or = false) of their matching values.

isUnique(array('field1', 'field2'), false));

Notice the false, if the 2nd arg is not set to false it won't work like you want it because it's using OR instead of AND then.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top