Borja Pombo
Borja Pombo

Reputation: 535

Symfony2 Doctrine 1062 Duplicate entry

I just modified one of my entities to set an sluggable field.

This is the code i added to my entity

/**
 * @var string
 *
 * @Gedmo\Slug(fields={"name"}, updatable=false)
 * @ORM\Column(name="slug", type="string", length=255, unique=true)
 */
private $slugEn;

Then i used the console commands doctrine:generate:entities and doctrine:schema:update --force but when i used it, the console returns me this message of error:

[PDOException] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'UNIQ_70F2BD0F989D9B62'

I know, the force fix is truncate the database and create another time but i need to fix it without truncate.

How can i fix it then?

Upvotes: 1

Views: 1924

Answers (2)

Francesco Abeni
Francesco Abeni

Reputation: 4265

I can see several possible solutions, depending on the type and the amount of existing entities.

  1. Make sure you have NOT empty "name" fields. The slug is generated from name and the error you get is because you have several entities with "name" empty.

  2. Use more than one field to build the slug, e.g. "id" so you make sure it's always valid and always unique.

  3. Use a custom method to create the slug where you create a random string when the provided name is empty.

Upvotes: 2

DerStoffel
DerStoffel

Reputation: 2633

You can disable your UniqueKey checks temporarely.

In MySQL you'll use:

SET UNIQUE_CHECKS=0;
SET FOREIGN_KEY_CHECKS=0;

// do stuff

SET UNIQUE_CHECKS=1;
SET FOREIGN_KEY_CHECKS=1;

Those are simple sql statements and can be executed as such.

No guarantees for data loss or loss of valid references and constraints.

Upvotes: 0

Related Questions