B
B
Bovv2018-03-29 11:33:50
Doctrine ORM
Bovv, 2018-03-29 11:33:50

Doctrine ORM what is the difference between EntityManager->merge() and EntityManager->persist()?

The Doctrine documentation describes that the merge() method creates a new object, copies its state, and adds it to the persistance context.
I've seen code like this many times:

$entity = $em->getRepository(...)->findOne($id);
if (null === $entity) {
    $entity = new Entity();
    $em->persist($entity);
} else {
    $entity->setGeneratedAt(new \DateTime());
    $em->merge($entity);
}

$em->flush();

The question is why $em->merge() is used, because the call is not assigned to any variable and no action is taken with the new entity, the $entity entity is not detached and is already in the persistance context.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stas Kuryan, 2018-12-18
@Stafox

Merge is absolutely not needed here. The one who used it in this place does not have a complete understanding of how the doctrine works.
A merge can be used when an entity has been dispatched and needs to be added again as tracked in the entity manager. And yes, it will be a new object with a new spl object hash

V
v0ff, 2018-08-31
@v0ff

in the first case, when the entity is not found, and the result is null, then you need to create a new object and persist it before writing
. And if the record is already found, just update it! those. merge.
and at the end sending for writing to the database, i.e. all requests are collected and sent in one big batch for writing to the database. and those mentioned above (in the example) and those that were specified in $em->persist(...) earlier !
In your example, it is well shown that the record is being updated - replacing the creation / generation date

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question