问题
I want to set up a unique constraint on the fields "username" and "email" but it doesn't work :
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Table(name="acteurs")
* @ORM\Entity(repositoryClass="UserBundle\Repository\ActeurRepository")
* @ORM\InheritanceType("JOINED")
* @UniqueEntity(fields="email", message="Cet email existe déjà.")
* @UniqueEntity(fields="username", message="Ce login existe déjà.")
*/
abstract class Acteur extends BaseUser { ... }
The form is validated by symfony and i get database error :
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du champ 'test@gmail.com' pour la clef 'UNIQ_B85835ACA0D96FBF'
What is wrong ?
回答1:
Sadly there is a bug in Symfony's Validation Component concerning UniqueEntity
using with inherited classes. It's already reported in 2012: https://github.com/symfony/symfony/issues/4087
I've never tried it, but you can workaround it using the repositoryMethod
-option.
/**
* @ORM\Table(name="acteurs")
* @ORM\Entity(repositoryClass="UserBundle\Repository\ActeurRepository")
* @ORM\InheritanceType("JOINED")
* @UniqueEntity(fields="email", message="Cet email existe déjà.", repositoryMethod="findByUniqueEmail")
* @UniqueEntity(fields="username", message="Ce login existe déjà.", repositoryMethod="findByUniqueUsername)
*/
abstract class Acteur extends BaseUser { ... }
And add this to your ActeurRepository
:
class ActeurRepository extends EntityRepository
{
public function findByUniqueEmail(array $criteria)
{
return $this->findBy($criteria);
}
public function findByUniqueUsername(array $criteria)
{
return $this->findBy($criteria);
}
}
来源:https://stackoverflow.com/questions/39773960/fosuserbundle-unique-entity-constraints