Home > Blockchain >  How to avoid SQL Exception of duplicated entry in Api-platform (Symfony)?
How to avoid SQL Exception of duplicated entry in Api-platform (Symfony)?

Time:10-23

I'm using Symfony 5.3 Api-platform and I have an User entity which has 3 unique indexes validators.

They are marked as @UniqueEntity.

...
* @UniqueEntity({"email", "anonymousGuid", "qrcode" })
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{

The properties also are marked as unique=true. I.e:

/**
 * @ORM\Column(type="string", length=180, unique=true, nullable=true)
 * @Groups ({"user_read","user_write"})
 * @Assert\Email
 */
private $email;

However, when trying to insert a new user using the api, it throws an SQL Exception instead of showing an exception in the proper API format.

{
  "@context": "/contexts/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'string' for key 'UNIQ_8D93D649A4FF23EC'",

Am I missing something?

Should I really need to add a manual validation?

CodePudding user response:

Reading the docs for UniqueEntity here:
https://symfony.com/doc/current/reference/constraints/UniqueEntity.html#fields
It would appear that the default option is a string of a single field name. To pass an array of fields I think you need to specify the option key:

// DON'T forget the following use statement!!!
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity(fields={"email", "anonymousGuid", "qrcode"})
 */

NOTE:

The above usage requires the combination of values in those fields to be unique, allowing the email to be used again if one of the other fields are different. If you want every user to have each of those fields to be unique individually (unique columns), then you should have three separate UniqueEntity entries, each with a single field:

use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity
 * @UniqueEntity("email")
 * @UniqueEntity("anonymousGuid")
 * @UniqueEntity("qrcode")
 */
  • Related