Doctrine2: Understanding On Delete Cascade
For seamless database maintenance, it's often necessary to automatically delete child records when the corresponding parent record is deleted. Doctrine2 supports this functionality through "On Delete Cascade," a feature that ensures child records are removed when their parent is.
Example Entities
Consider the following entities:
<code class="php">class Child { /** @ORM\ManyToOne(targetEntity="Father", cascade={"remove"}) */ private $father; } class Father { /** @ORM\Id @ORM\GeneratedValue */ private $id; }</code>
The Problem: Missing Database Cascade
While the code establishes a relationship between Child and Father with a "remove" cascade, the database lacks the "On Delete Cascade" constraint.
Solution: Database-Level Cascade
To implement true On Delete Cascade, add onDelete="CASCADE" to the child's join column:
<code class="php">/** @ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE") */</code>
This specifies that when a row is deleted from the Father table, all matching rows in the Child table will be automatically deleted.
Caution: Understand Cascades
It's important to note the distinction between ORM-level and database-level cascades. ORM-level cascades operate within Doctrine's UnitOfWork and do not affect the database structure, while database-level cascades create physical constraints in the database. In the current example, the cascade={"remove"} is an ORM-level cascade that will trigger a recursive deletion in the UnitOfWork, but it won't result in the desired database behavior.
The above is the detailed content of Doctrine2: How Do I Implement On Delete Cascade for seamless database maintenance?. For more information, please follow other related articles on the PHP Chinese website!