ChatGPT解决这个技术问题 Extra ChatGPT

Doctrine: cascade="remove" vs orphanRemoval=true

What is the difference between the 2 options above? When is it preferable to choose each option?


m
marco-fiset

The basic difference between them is:

When using the orphanRemoval=true option Doctrine makes the assumption that the entities are privately owned and will NOT be reused by other entities. If you neglect this assumption your entities will get deleted by Doctrine even if you assigned the orphaned entity to another one.

Say your User has one-to-many relation to Comment. If you are using cascade="remove", you can remove the reference for Comment from one User, and then attach that Comment to another User. When you persist them, they will be correctly saved. But if you are using orphanRemoval=true, even if you will remove given Comment from one User, and then attach to another User, this comment will be deleted during persist, because the reference has been deleted.


@a2ad2d what does "privately owned" means? I know that orphanRemoval=true can by the way be used in ManyToMany Relationship
@Aleqxs can you provide an example?
@a2ad2d Category Entity and Article Entity in a ManyToMany relationship. see asked question on this subject here and some of the test I did to delete in cascade here
@Aleqxs Sorry, but it seems that in case of ManyToMany, orphanRemoval doesn't make sense
@a2ad2d but it is written that it "works with Many-To-Many associations" in the offical doctrine documentation This is why I wonder what exactly means "privatly own"