Search code examples
doctrineforeign-keyssymfony4

Symfony4: Delete issue when OneToMany and OneToOne on the same entity


I have a Trick entity who contains a OneToOne ($mainImage) and OneToMany ($images) association with the same entity. I can't delete a Trick: it tells me there is a foreign key constraint. Of course, because the $mainImage has a FK for Image, and Image has a foreign key for Trick !

If I manually empty the $mainImage and flush before deletion, it works, but it's to tricky, I can't bear such irrespect toward the clineliness of my code!

I think there is a thing to do around "cascade" or "orphanRemoval" attributes of Doctrine but, as you can see below, I've tried them all and I still get the error.

class Trick
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="trick", orphanRemoval=true, cascade={"persist", "remove"})
     */
    private $images;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Image", cascade={"persist", "remove"}, orphanRemoval=true)
     * @JoinColumn(name="main_image_id", referencedColumnName="id", onDelete="set null")
     */
    private $mainImage;

}

and an Image entity:

class Image
{
    /**
     * @ORM\ManyToOne(targetEntity="Trick", inversedBy="images")
     * @ORM\JoinColumn(nullable=false)
     */
    private $trick;
}

Could someone help me please ? You'll get all my gratitude !


Solution

  • You have to remove the element in your setter first

    public function setImage($image){
        if($this->image !== null) // first remove old one from images
            $this->images->removeElement($this->image);
        $this->image = $image;
    }
    

    the same holds vice versa: if you want to remove an image from the array, first check if its your current image and delete it too.