叶栅 = {“ remove”} VS 孤立删除 = true VS ondelete = “ CASCADE

我试图收集一些关于以下方法的信息,以便在删除父实体时自动删除子实体。似乎最常见的方法是使用这三个注释之一: cascade={"remove"}orphanRemoval=trueondelete="CASCADE"

我对第三个有点困惑: ondelete="CASCADE",因为官方文件中对这个的解释非常少) ,我希望有人能够 向我确认以下信息我收集和理解从我的网络研究和经验..。

它有什么用?

cascade={"remove"} = = > 当拥有侧实体为。即使你在一个 ManyToMany与其他拥有侧实体。

  • 应该在收集时使用(因此在 OneToManyManyToMany关系中)
  • 实施

orphanRemoval=true 当拥有侧实体为 AND 且不再连接到任何其他拥有侧实体时,相反方的实体将被删除。(参考文献。< a href = “ http://ism-orm.readthedocs.org/en/last/reference/xml-mapping.html

  • 实施
  • 可与 OneToOneOneToManyManyToMany一起使用

onDelete="CASCADE" = = > 这将把 On Delete Cascade 添加到数据库中的外键列

  • 这个策略是有点棘手,但可以是非常强大和快速。(参考文献。但还没有看到更多的解释)
  • ORM 必须做更少的工作(与前两种方法相比) ,因此应该具有更好的性能。

其他资料

  • 所有这3种方法都是在双向关系实体(对吧)上实现的
  • 使用 cascade={"remove"}完全绕过任何外键 onDelete = CASCADE

关于如何在代码中使用它的示例

  • orphanRemovalcascade={"remove"}在反向实体类中定义。
  • ondelete="CASCADE"在所有者实体中定义
  • 您也可以只编写 @ORM\JoinColumn(onDelete="CASCADE"),并让学说处理列名

级联 = {“移除”}

/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact", cascade={"remove"})
*/
protected $Phonenumbers

移除孤儿 = 真

/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact", orphanRemoval=true)
*/
protected $Phonenumbers

OnDelete = “ CASCADE”

/**
* @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
* @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
*/
protected $contact;
54000 次浏览

onDelete="CASCADE" is managed by the database itself. cascade={"remove"} is managed by doctrine.

onDelete="CASCADE" is faster because the operations are performed on database level instead by doctrine. The removing is performed by the database server and not Doctrine. With cascade={"remove"} doctrine has to manage the entity itself and will perform extra checks to see if it doesn't have any other owning entities. When no other exists it will delete the entity. But this creates overhead.


cascade={"remove"}

  • the entity on the inverse side is deleted when the owning side entity is. Even if you are in a manytomany with other owning side entity. No, if the entity is owned by something else. It won't be deleted.
  • should be used on collection (so in OneToMany or ManyToMany relationship)
  • implementation in the ORM

orphanRemoval="true"

  • the entity on the inverse side is deleted when the owning side entity is AND it is not connected to any other owning side entity anymore. Not exactly, this makes doctrine behave like it is not owned by an other entity, and thus remove it.
  • implementation in the ORM
  • can be used with OneToOne, OnetoMany or ManyToMany

onDelete="CASCADE"

  • this will add On Delete Cascade to the foreign key column IN THE DATABASE
  • This strategy is a bit tricky to get right but can be very powerful and fast. (this is a quote from doctrine official tutorial... but haven't seen much more explaination)
  • ORM has to do less work (compared to the two previous way of doing) and therefore should have better performance.