Home > Backend Development > PHP Tutorial > How to Implement \'on Delete Cascade\' in Doctrine2?

How to Implement \'on Delete Cascade\' in Doctrine2?

Mary-Kate Olsen
Release: 2024-11-03 00:19:02
Original
819 people have browsed it

How to Implement

On Delete Cascade Implementation with Doctrine2

When utilizing Doctrine2 for managing database relationships, you may encounter the need to automatically delete child rows upon the deletion of a parent row. This is achieved through the "on delete cascade" option.

In your specific example, after defining your Child and Father entities, you're encountering an issue where the "on delete cascade" option isn't being created in the database. This is likely due to using ORM-level cascades (specified as cascade={"remove"} in the association).

ORM-Level Cascades

ORM-level cascades handle the deletion process within the UnitOfWork, affecting the object structure but not the database itself. When removing an object using ORM-level cascades, the UnitOfWork iterates through associated objects and removes them as well.

Database-Level Cascades

In contrast to ORM-level cascades, database-level cascades require specifying onDelete="CASCADE" on the join column of the association. This approach adds the "on delete cascade" constraint to the foreign key column in the database, ensuring that child rows are automatically deleted when the parent row is removed.

To correct the issue, modify your Child entity as follows:

<code class="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\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")
     *
     * @var father
     */
    private $father;
}</code>
Copy after login

The above is the detailed content of How to Implement \'on Delete Cascade\' in Doctrine2?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template