Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 EntityManager Updating without persist

As you can see below, I do not "persist" at all. But the changes I make are registering. I would appreciate your help.

$entityManager = $this->getDoctrine()->getManager(); $entity = $entityManager->getRepository(City::class)->find(1); $entity->setName("debug name"); $entityManager->flush();

like image 691
Murat SAÇ Avatar asked Oct 26 '25 03:10

Murat SAÇ


1 Answers

You have to call method persist() when initializing a new object, like new City(). When you fetch object from database with find() it already has some metadata.


From doctrine website:

Doctrine uses the Identity Map pattern to track objects. Whenever you fetch an object from the database, Doctrine will keep a reference to this object inside its UnitOfWork. The array holding all the entity references is two-levels deep and has the keys “root entity name” and “id”.

Here is example from doctrine:

When you call EntityManager#flush Doctrine will ask the identity map for all objects that are currently managed. This means you don’t have to call EntityManager#persist over and over again to pass known objects to the EntityManager. This is a NO-OP for known entities, but leads to much code written that is confusing to other developers.

The following code WILL update your database with the changes made to the Person object, even if you did not call EntityManager#persist:

<?php
$user = $entityManager->find("Person", 1);
$user->setName("Guilherme");
$entityManager->flush();
like image 95
ArtOsi Avatar answered Oct 29 '25 04:10

ArtOsi