Question

How to automatically generate a primary key in Symfony2/Doctrine2 ?

I have all my entities and database made.

In my Symfony2 controller, I do :

<?php
/**
 * @Route("/myroute", name="myroute")
 * @Template()
 */
public function myrouteAction()
{
    /* Page de Création d'un retrait ou d'une réexpédition. */
    $obj = new Utilisateur();
    $obj->setUsermail('contact@mydomain.com');
    $obj->setUserpass('coucou');
    $obj->setUservalide('1');

    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($obj);
    $em->flush();

    // [...]
}

It is for testing. The first time all went right (Utilisateur table was empty). Now, when I call again this function, I get :

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' 500 Internal Server Error - PDOException

I just want Symfony-Doctrine-Mysql to automatically increment the identifier.

Was it helpful?

Solution

Hopefully this helps: assuming you are using annotations and Doctrine ORM, You need to set the strategy to auto on your object - from the documentation (http://symfony.com/doc/current/book/doctrine.html)

/**
 * @ORM\Entity
 * @ORM\Table(name="product")
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
-->  * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

remember to update your database schema after you have modified the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top