简体   繁体   中英

Phalcon PHP: test Uniqueness on a natural key?

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM