简体   繁体   English

如何阻止Doctrine 2在Symfony 2中缓存结果?

[英]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. 我希望能够检索实体的现有版本,以便将其与最新版本进行比较。 Eg Editing a file, I want to know if the value has changed since being in the DB. 例如,编辑文件,我想知道自从进入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? 有谁知道如何绕过这个缓存?

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. Doctrine在EntityManager中存储检索到的实体的引用,因此它可以通过它的id返回实体而不执行另一个查询。

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. 但请注意,由于$ post实体已分离,因此如果要再次保留它,则必须使用 - > merge()方法。

You can also use the refresh method, which refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted. 您还可以使用refresh方法,该方法从数据库刷新实体的持久状态,覆盖尚未保留的任何本地更改。 Something like: 就像是:

$entityManager = $this->get('doctrine')->getEntityManager();
$repository = $entityManager->getRepository('KnowledgeShareBundle:Post');
$post = $repository->find(1);

$entityManager->refresh($post);

now $post contains the last version from database. 现在$ post包含数据库的最新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM