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

Ell*_*oad 27 php caching symfony doctrine-orm

我希望能够检索实体的现有版本,以便将其与最新版本进行比较.例如,编辑文件,我想知道自从进入数据库以来该值是否已更改.

    $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"
Run Code Online (Sandbox Code Playgroud)

有谁知道如何绕过这个缓存?

小智 45

这是正常的行为.

Doctrine在EntityManager中存储检索到的实体的引用,因此它可以通过它的id返回实体而不执行另一个查询.

你可以这样做:

$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);
Run Code Online (Sandbox Code Playgroud)

但请注意,由于$ post实体已分离,如果要再次保留它,则必须使用 - > merge()方法.

  • 谢谢你.快速提示 - 如果您需要分离所有实体(例如,在非绝缘测试中),您可以使用`$ entityManager-> clear()`. (12认同)
  • 美味,'分离'是完美的. (4认同)

小智 13

您还可以使用该refresh方法从数据库刷新实体的持久状态,从而覆盖尚未保留的任何本地更改.就像是:

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

$entityManager->refresh($post);
Run Code Online (Sandbox Code Playgroud)

现在$ post包含数据库的最新版本.