Marvin
Marvin

Reputation: 157

Symfony2 Duplicate Entry - but why?

I get following exception:

An exception occurred while executing 'INSERT INTO tasks (task_title, task_description, task_priority, task_type, user) VALUES (?, ?, ?, ?, ?)' with params ["efswedfgvswde", "ewdfweds", "Normal", 14, 13]:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '13' for key 'UNIQ_505865978D93D649'

Here I insert my form Type into the database:

$task = new Task();
$form = $this->createForm(new TaskType(), $task);

$form->handleRequest($request);

if($form->isValid()):

        $em = $this->get('doctrine')->getManager();
        $em->persist($task);
        $em->flush();

        return  $this->redirect($this->generateUrl('add_task'));

endif;

This is the field USER in my Task Entity:

/**
 * @var User
 * @Assert\Type(type="Seotool\MainBundle\Entity\User")
 * @ORM\OneToOne(targetEntity="User")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
protected $user;

Why is it NOT possible to add 2 entrys into the Table "Task" with same values of field "user" ? Actually in my database there is one entry with user value = 13. When I add another entry in my database with user = 13 I get this exception. Why is it? I have not defined, that User is unique ?!

Thats ID from User Entity:

/**
 * @var integer $id
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

Upvotes: 0

Views: 1368

Answers (1)

gregory90
gregory90

Reputation: 569

You have wrong association mapping as @Qoop stated.

One user can have many tasks - that translates to OneToMany association from User entity.
Many tasks may belong to one user - that translates to ManyToOne association from Task entity.

Provided code indicates that association is unidirectional (there's no $tasks field in User entity) so there's only need for ManyToOne mapping from Task entity.

Your mapping should look like this:

/**
 * @var User
 * @Assert\Type(type="Seotool\MainBundle\Entity\User")
 * @ORM\ManyToOne(targetEntity="User")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

You can learn more about associations in Doctrine here.
There's also similar problem on StackOverflow here.

Upvotes: 3

Related Questions