Multi-column unique key validation in CakePHP

CakePHP (at least in v1.3) by itself does not support a straight-forward multiple column unique key validation, but in a few steps you can have an elegant solution to this problem. In order to create a validation for multi-column unique key, you can use the CakePHP’s custom validation logic by creating a function which will do the validation, and defining the rule in your validations array of your model.

Unique key validation function

In my opinion the best place to be put this method is in your app_model (you can put it in your model class, but this way you can use this in all your models).

Add this function to your /your_app_root/app/models/app_model.php file:

function checkUnique($data, $fields)
{
    // check if the param contains multiple columns or a single one
    if (!is_array($fields))
    {
        $fields = array($fields);
    }

    // go trough all columns and get their values from the parameters
    foreach($fields as $key)
    {
        $unique[$key] = $this->data[$this->name][$key];
    }

    // primary key value must be different from the posted value
    if (isset($this->data[$this->name][$this->primaryKey]))
    {
        $unique[$this->primaryKey] = "<>" . $this->data[$this->name][$this->primaryKey];
    }

    // use the model's isUnique function to check the unique rule
    return $this->isUnique($unique, false);
}

This function basically receives the form parameters containing the values to be added/updated, creates a key-value pair array containing the name of the field in the unique key, and it’s value, adds the primary key and its value to the check (must be different from an existing one, or your updated wouldn’t work), and uses the CakePHP built-in function “isUnique” to do the validation.

More on creating a multiple column unique key validation in CakePHP…