dovstone
dovstone

Reputation: 144

Symfony 4: How to remove doctrine integrity constraint violation?

My Post entity looks like this:

<?php

// ...

class Post
{

 /**
 * The ID generated manually.
 *
 * @ORM\Id
 * @ORM\Column(type="integer", length=3)
 */
private $id;

//...

/**
 * One Post has One Post.
 *
 * @ORM\OneToOne(targetEntity="DovStone\Bundle\BlogAdminBundle\Entity\Post", fetch="EAGER")
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
private $parent;

One insertion works as expected and I can even get the parent $post->getParent() of a given post.

A problem occures when I try to make another post insertion which has the same parent as the previous post inserted successfuly.

I'll make this following example so you can get clearly what I mean:

Insertion #1:
Id: 613
Parent: NULL //success

Insertion #2:
Id: 156
Parent: 613 //success

Insertion #3:
Id: 156
Parent: 613 //fail

Insertion #3 returns me SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed because I think insertion #2 has already its parent it as 613.

So what should I do to tell doctrine parent_id column must not be unique as id column.

Upvotes: 1

Views: 1481

Answers (2)

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

You need to change your relation from

@ORM\OneToOne

to

@ORM\ManyToOne

Like this:

@ORM\ManyToOne(targetEntity="DovStone\Bundle\BlogAdminBundle\Entity\Post", inversedBy="DovStone\Bundle\BlogAdminBundle\Entity\Post", fetch="EAGER")
@ORM\JoinColumn(name="parent_id", referencedColumnName="id")

Upvotes: 3

Andrea Pinti
Andrea Pinti

Reputation: 123

If your $parent class could have more than one child, it should be usually mapped as ManyToOne relation

Upvotes: 1

Related Questions