Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Doctrine 2 from caching a result in Symfony 2?

I want to be able to retrieve the existing version of an entity so I can compare it with the latest version. E.g. Editing a file, I want to know if the value has changed since being in the DB.

    $entityManager = $this->get('doctrine')->getEntityManager();     $postManager = $this->get('synth_knowledge_share.manager');      $repository = $entityManager->getRepository('KnowledgeShareBundle:Post');     $post = $repository->findOneById(1);       var_dump($post->getTitle()); // This would output "My Title"     $post->setTitle("Unpersisted new title");      $existingPost = $repository->findOneById(1); // Retrieve the old entity      var_dump($existingPost->getTitle()); // This would output "Unpersisted new title" instead of the expected "My Title" 

Does anyone know how I can get around this caching?

like image 865
Elliot Coad Avatar asked Oct 31 '11 15:10

Elliot Coad


1 Answers

It's a normal behavior.

Doctrine stores a reference of the retrieved entities in the EntityManager so it can return an entity by it's id without performing another query.

You can do something like :

$entityManager = $this->get('doctrine')->getEntityManager(); $repository = $entityManager->getRepository('KnowledgeShareBundle:Post'); $post = $repository->find(1);  $entityManager->detach($post);  // as the previously loaded post was detached, it loads a new one $existingPost = $repository->find(1); 

But be aware of that as the $post entity was detached, you must use the ->merge() method if you want to persist it again.

like image 112
Herzult Avatar answered Sep 20 '22 14:09

Herzult