如何阻止 Doctrine 2 在 Symfony 2 中缓存结果?
我希望能够检索实体的现有版本,以便可以将其与最新版本进行比较。例如,编辑文件时,我想知道该值自进入数据库以来是否已更改。
$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"
有谁知道我如何绕过这个缓存?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正常行为。
Doctrine 将检索到的实体的引用存储在 EntityManager 中,因此它可以通过实体的 id 返回实体,而无需执行其他查询。
您可以执行以下操作:
但请注意,由于 $post 实体已分离,如果您想再次保留它,则必须使用 ->merge() 方法。
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 :
But be aware of that as the $post entity was detached, you must use the ->merge() method if you want to persist it again.
您还可以使用
refresh
方法,该方法从数据库刷新实体的持久状态,覆盖任何尚未持久的本地更改。像这样:
现在 $post 包含数据库中的最后一个版本。
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.Something like:
now $post contains the last version from database.