Phalcon PHP: test Uniqueness on a natural key?

732 views Asked by At

I've got some code like this:

$this->validate(new \Phalcon\Mvc\Model\Validator\Uniqueness(['field' => $field]));
if (true == $this->validationHasFailed()) {
    throw new SpecialInternalUniqueException();
}

This works for all columns except for natural Primary Keys. That is, Primary Keys that are not surrogate keys (auto-incrementing integers). For example, in the job_titles table, the natural key column is "job_title" - which, in our case, refers to the name of the job title. This name should be unique, and I want to be able to check for that in the code prior to saving. However, Phalcon happily ignores it, somehow.

I'm actually setting up a unit test for this right now and doing something similar to the following:

$job_title = new JobTitles();
$job_title->job_title = 'Unique Test';
$job_title->description = 'Desc A';
$job_title->save();

$job_title2 = new JobTitles();
$job_title2->job_title = 'Unique Test';
$job_title->description = 'Desc B';
$job_title->save();

The exception never gets thrown. What ends up in the database is a single column for the first Unique test with Desc A, and no record for the second one. But I don't get a thrown exception.

Any thoughts?

EDIT:

Also, I've tried with the ->create() function in place of the save() function.

1

There are 1 answers

5
cvsguimaraes On

First you should be aware that in the default behavior those validations are created from the actual database schema right after the model class is initialized; you're not supposed to add them manually in that case.

In other words, the default meta-data strategy for models is the Database Introspection Strategy

So a exception will only be raised if the job_title field is already indexed for uniqueness checking in the database scheme. If you aren't able to actually create this PK in the database, you may change the default meta-data strategy for your models and them set the metadata manually (sigh).