Answer the question
In order to leave comments, you need to log in
Doctrine: how to add exception for UniqueEntity?
There is a questionnaire. The completed form is saved in Answer
.
Limited duplication $user
and $question
using UniqueEntity
.
There is a property $file
. If it's not null, then UniqueEntity should be avoided and duplication allowed. Or specify $question
an id that should not be subject to the duplication restriction.
How to add such exception for UniqueEntity? Other offers?
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @UniqueEntity({"user", "question"});
* @ORM\Entity(repositoryClass="App\Repository\AnswerRepository")
*/
class Answer
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="answers")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="answers")
*/
private $question;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $file;
public function getId(): ?int
{
return $this->id;
}
public function getUser(): ?user
{
return $this->user;
}
public function setUser(user $user): self
{
$this->user = $user;
return $this;
}
public function getQuestion(): ?question
{
return $this->question;
}
public function setQuestion(?question $question): self
{
$this->question = $question;
return $this;
}
public function getFile()
{
return $this->file;
}
public function setFile($file): self
{
$this->file = $file;
return $this;
}
}
Answer the question
In order to leave comments, you need to log in
Do not use UniqueEntity, but directly validate $request itself and already there dance from various conditions. If you work with the validator correctly, then it will not skip the constraints that you specify.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question