We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Uniqueness Validator not working

I'm doing some validation of a model, and the Uniqueness validator is creating a weird query.

My custom validation() method looks like this:

public function validation(){
    $Validator = new Validation();
    $Validator->add(
        'name',
        new Uniqueness(['message'=>'An Event Type with that name already exists.'])
    );

    return $this->validate($Validator);
}

The model is "EventType".

When I check the query log after validating a model with the name "CourseAdd", this is the query that gets generated:

SELECT 
    COUNT(*) AS `rowcount` 
FROM 
    `event_type` 
WHERE 
    `event_type`.`name` = 'CourseAdd' AND 
    `event_type`.`name` <> 'CourseAdd'

Of course that returns 0, so the validation passes - even though there's already a record with a name of 'CourseAdd'.

I don't know of any reason why the query should be built like that, so I'm guessing it's a Phalcon bug - but I thought I'd ask here first.

Hi @Dylan it's so strange. Check your primary key definition. Other way use Uniqueness from incubator using exclude options

Good luck



145.0k
Accepted
answer
edited Sep '17

Hmmm it looks like name is primary key? If yes then when record alredy exists in database then phalcon will ignore current value of primary key attribute. So we don't have record itself counted when doing update. Im guessing you need to update your schema like add id to change primary key. You can use findFirsyByName to still find it pretty easly without creating parameters for findFirst.

edited Oct '17

Changing the primary key worked.

Is this behaviour documented somewhere? It seems like a non-obvious side-affect.

Not documented beacause it's kind of obvious. If you do update on current model and you have uniqueness you don't want current model to be counted, right? Otherwise you would have always non unique attribute when updating.

Not documented beacause it's kind of obvious. If you do update on current model and you have uniqueness you don't want current model to be counted, right? Otherwise you would have always non unique attribute when updating.

Yes, that makes sense, but it's not obvious to me at all that this behaviour is because of that. If I set up a uniqueness validator, it means I just want the validated column to be unique - period. What role the column has in the database shouldn't matter.

It should matter, beacause you don't want current value of current record to be part of uniqueness when updating model. So if column is primary key and you are doing uniqueness on it then obviously you don't want records with current primary key to be count.