Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question