On delete cascade with doctrine2

Viewed 185497

I'm trying to make a simple example in order to learn how to delete a row from a parent table and automatically delete the matching rows in the child table using Doctrine2.

Here are the two entities I'm using:

Child.php:

<?php

namespace Acme\CascadeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="child")
 */
class Child {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @ORM\ManyToOne(targetEntity="Father", cascade={"remove"})
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="father_id", referencedColumnName="id")
     * })
     *
     * @var father
     */
    private $father;
}

Father.php

<?php
namespace Acme\CascadeBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="father")
 */
class Father
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
}

The tables are correctly created on the database, but the On Delete Cascade option it's not created. What am I doing wrong?

3 Answers

While the proper way to delete on cascade is using @Michael Ridgway answer, there is also the possibility to listen do doctrine events to do the same thing.

Why ? Well you may want to do additional things when removing a father entity, maybe using a soft deleteable on some or hard removing others. You could also reaffect his children to another entity in case where you want to keep it and affect it to a parent entity etc...

So the way to do that would be to listen the doctrine event preRemove.

preRemove - The preRemove event occurs for a given entity before the respective EntityManager remove operation for that entity is executed. It is not called for a DQL DELETE statement.

Note that this event will be called only when using ->remove.

Start by creating your event subscriber/listener to listen to this event:

<?php

namespace App\EventSubscriber;

use Doctrine\Common\EventSubscriber;
use App\Repository\FatherRepository;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use App\Entity\Father;
use App\Entity\Child;

class DoctrineSubscriber implements EventSubscriber
{
    private $fatherRepository;

    public function __construct(FatherRepository $fatherRepository) 
    {
        $this->fatherRepository = $fatherRepository;
    }
    
    public function getSubscribedEvents(): array
    {
        return [
            Events::preRemove => 'preRemove',
        ];
    }
    
    public function preRemove(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof Father) {
            //Custom code to handle children, for example reaffecting to another father:
            $childs = $entity->getChildren();
            foreach($childs as $child){
                $otherFather = $this->fatherRepository->getOtherFather();
                child->setFather($otherFather);
            }
        }
    }
}

And don't forget to add this EventSubscriber your services.yaml

  App\EventSubscriber\DoctrineSubscriber:
    tags:
      - { name: doctrine.event_subscriber }

In this example, the father will still be deleted but the children will not by having a new father. For example, if the entity Father add other family members we could reaffect the children to someone else from the family.

Related