Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Doctrine Cascade Operations

persist & remove

You are correct about cascade={"persist"} meaning that persisting entity A, Doctrine will also persist all B entities in the Collection.

You are also correct about cascade={"remove"} meaning that removing entity A, Doctrine will also remove all B entities in the Collection.
But I doubt you would ever want to use this on a ManyToMany association, because when you remove entity A that cascades this operation to all B entities, those B entities might be associated to other A entities.

detach & merge

You are not correct about cascade={"detach"} and cascade={"merge"}:

Adding/removing entities from the Collection is something you need to do (in your code). Read about that here.

Detach means that you detach an entity from the EntityManager. The EntityManager will no longer manage that entity. This makes a detached entity the same as a newly instantiated entity, except that it's already in the database (but you made the EntityManager unaware of that).

In other words: cascade={"detach"} means that detaching entity A, Doctrine will also detach all B entities in the Collection.

Merge is the opposite of detach: You will merge a detached entity back into the EntityManager.
Do note that merge() will actually return a new managed object, the detached object you passed to it remains unmanaged.