I have a Uniqueness validator on a text field in my model. When I try to insert a new record with the same text as a previous record, the validations works and the new record does not get inserted. However, when I update an existing record with a text that is not unique, the validation does not seem to execute since the record gets updated with the non-unique text.
Am I doing something wrong here?
Sample code to reproduce:
<?php
$di = new Phalcon\DI\FactoryDefault();
$di->setShared('db', function () {
return new \Phalcon\Db\Adapter\PDO\Sqlite(array(
'dbname' => ':memory:'
));
});
class Test extends \Phalcon\Mvc\Model
{
public $mappedPrimaryKey;
public $mappedData;
public function columnMap()
{
// Keys are the real names in the table and
// the values their names in the application
//
return array(
"primaryKey" => "mappedPrimaryKey",
"data" => "mappedData"
);
}
public function validation()
{
$validator = new Phalcon\Validation();
$validator->add( "mappedData",
new Phalcon\Validation\Validator\Uniqueness( array(
"message" => "Data must be unique"
)));
return $this->validate( $validator );
}
}
use \Phalcon\Db\Column as Column;
$di['db']->createTable(
'test',
null,
[
'columns' => [
new Column(
'primaryKey',
[
'type' => Column::TYPE_INTEGER,
'notNull' => true,
'autoIncrement' => true,
'primary' => true,
]
),
new Column(
'data',
[
'type' => Column::TYPE_TEXT,
'notNull' => true,
]
)
]
]
);
$testObject1 = new Test;
$testObject1->mappedPrimaryKey = 1;
$testObject1->mappedData = "Object 1";
$testObject1->save();
$testObject2 = new Test;
$testObject2->mappedPrimaryKey = 2;
$testObject2->mappedData = "Object 2";
$testObject2->save();
$allRecords = Test::find();
foreach ( $allRecords as $record )
{
echo $record->mappedPrimaryKey . ": " . $record->mappedData . "\n";
}
echo "\n";
$result = Test::findFirst( "mappedPrimaryKey = 1" );
$result->mappedData = "Object 2"; // Not unique
$result->save();
$allRecords = Test::find();
foreach ( $allRecords as $record )
{
echo $record->mappedPrimaryKey . ": " . $record->mappedData . "\n";
}
echo "\nPhalcon Version: ", Phalcon\Version::get(), "\n";
My output:
1: Object 1
2: Object 2
1: Object 2
2: Object 2
Phalcon Version: 3.4.0