\Phalcon\Mvc\Model\Validator\Uniqueness with namespaces
-
03-07-2021 - |
Question
I am get the following Phalcon\Db\Exception below when using \Phalcon\Mvc\Model\Validator\Uniqueness validator with a model that is a namespace. Looks like validator class is not using getSource method from the Model when building the supporting query.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near app\dao\users WHERE username = 'nhidalgo' AND id <> ''' at line 1 when executing SELECT COUNT(*) AS rowcount FROM app\dao\users WHERE username = 'nhidalgo' AND id <> ''
My code is as follows:
<?php
namespace App\Dao;
use Phalcon\Mvc\Model\Validator\Inclusionin;
use Phalcon\Mvc\Model\Validator\Uniqueness;
class Users extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->setSource('users');
}
public function validation()
{
$this->validate(new Uniqueness(
array(
"field" => "username",
"message" => "Username must be unique"
)
));
$this->validate(new Uniqueness(
array(
"field" => "email",
"message" => "Email must be unique"
)
));
return !$this->validationHasFailed();
}
}
La solution
The documentation states that if you use namespaces you MUST implement the method that returns the table name.
public function getSource()
{
return 'users';
}
setSource only changes the mapped table for a single instance, while implementing getSource makes the source available for every instance created.