我正在尝试一个简单的例子,以了解如何从父表中删除一行,并使用Doctrine2自动删除子表中的匹配行。
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:
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
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?
推荐答案在Doctrine中有两种级联:
There are two kinds of cascades in Doctrine:
1)ORM级别 - 在关联中使用 cascade = {remove} - 这是在UnitOfWork中完成的计算,不影响数据库结构。当您删除对象时,UnitOfWork将遍历关联中的所有对象并将其删除。
1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.
2)数据库级别 - 使用 onDelete = CASCADE在关联的joinColumn中 - 这将添加On Delete Cascade到数据库中的外键列:
2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:
@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")我还想指出,现在你有你的cascade = {删除}的方式,如果你删除一个Child对象,这个级联将删除Parent对象。显然不是你想要的。
I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.
更多推荐
删除级联与doctrine2
发布评论