Я пытаюсь использовать ограничение уникальной сущности в своей пользовательской сущности, но почему-то это не работает. Я по-прежнему получаю сообщение об ошибке дублирования ключа.
Это мой пользовательский объект:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Table(name = "Users")
* @ORM\Entity(repositoryClass = "App\Repository\UserRepository")
* @UniqueEntity(
* fields = {"email", "username"}
* )
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* @ORM\Column(type = "integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy = "AUTO")
*/
public $id;
/**
* @ORM\Column(type = "string", length=25, unique=true)
*/
public $username;
/**
* @ORM\Column(type = "string", length=64)
*/
public $password;
/**
* @ORM\Column(type = "string", length=128, unique=true)
* @Assert\Email()
*/
public $email;
/**
* @ORM\Column(name = "is_active", type = "boolean")
*/
public $isActive;
/**
* @ORM\Column(name = "roles", type = "array")
*/
public $roles = [];
/**
* @ORM\OneToOne(targetEntity = "App\Entity\UserDetails", mappedBy = "user", cascade = {"persist", "remove"})
*/
private $userDetails;
/**
* @ORM\ManyToMany(targetEntity = "App\Entity\Assignment", mappedBy = "user")
*/
private $assignments;
public function __construct()
{
$this->isActive = true;
$this->assignments = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid('', true));
}
/**
* @param mixed $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt and argon2i algorithms don't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
public function getRoles()
{
$roles = $this->roles;
if (!in_array('ROLE_USER', $roles)) {
$roles[] = 'ROLE_USER';
}
return $roles;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
public function setRoles(array $roles)
{
$this->roles = $roles;
}
public function eraseCredentials()
{
}
/** @see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
$this->isActive
// see section on salt below
// $this->salt,
));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
$this->isActive
// see section on salt below
// $this->salt
) = unserialize($serialized, ['allowed_classes' => false]);
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
public function getUserDetails(): ?UserDetails
{
return $this->userDetails;
}
public function setUserDetails(UserDetails $userDetails): self
{
$this->userDetails = $userDetails;
// set the owning side of the relation if necessary
if ($this !== $userDetails->getUser()) {
$userDetails->setUser($this);
}
return $this;
}
/**
* @return Collection|Assignment[]
*/
public function getAssignments(): Collection
{
return $this->assignments;
}
public function addAssignment(Assignment $assignment): self
{
if (!$this->assignments->contains($assignment)) {
$this->assignments[] = $assignment;
$assignment->addUser($this);
}
return $this;
}
public function removeAssignment(Assignment $assignment): self
{
if ($this->assignments->contains($assignment)) {
$this->assignments->removeElement($assignment);
$assignment->removeUser($this);
}
return $this;
}
}
При отправке формы я получаю следующее сообщение об ошибке:
An exception occurred while executing 'INSERT INTO Users (username, password, email, is_active, roles) VALUES (?, ?, ?, ?, ?)' with params ["sanderbakker", "$2y$13$evlC1NcG9BIdgeBRuBqCKu4uqt4Edsp24SEUIiYF3vg6rp0tEhHdm", "[email protected]", 1, "a:1:{i:0;s:10:\"ROLE_ADMIN\";}"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'sanderbakker' for key 'UNIQ_D5428AEDF85E0677'
Эта ошибка не появится, если я использую только один атрибут в качестве ограничения. Например, только атрибут имени пользователя или атрибут электронной почты
То же, что: stackoverflow.com/questions/8491675/…






Именно так работает ограничение UniqueEntity. Он добавляет элемент управления комбинацией имени пользователя и электронной почты. Если вы пытаетесь вставить запись, содержащую и адрес электронной почты, и имя пользователя, уже присутствующие в вашей таблице, orm вызывает исключение. Вы можете проверить с помощью select, существует ли комбинация уже до сброса или, если хотите, обработать, что вы можете вставить свою операцию сброса в блок try / catch, подобный этому
try {
$em->flush();
} catch (Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
// handle it here maybe returning an error to the UI
}
Ага. Добавьте два ограничения. Один для имени пользователя и один для электронной почты. Ограничение в том виде, в каком оно есть сейчас, гласит, что комбинация имени пользователя и адреса электронной почты должна быть уникальной.