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>
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!