我长期使用基于 SQL 查询的数据库访问级别。但现在我决定使用 ORM Doctrine2。目前,我对实体工作流程有一个概念上的误解。
最好的例子描述:
try {
$user = $entityManager->find('User', 1);
$user->setName('New name');
$entityManager->flush();
}
catch (...)
{
// !we are here: changes failed and $user-row in DB was not updated
}
// ...
$user = $entityManager->find('User', 1);
$user->setOther('Other');
$entityManager->flush(); // <- in this request both [other] and [name] fields will be updated to DB, but only [other] update expected
在第一个代码块中,我获取了 $user 对象。更改了 [name] 并尝试保存它,但失败了。在第二个 block (与第一个 block 无关)中,我再次获取了 $user 对象。但是 ORM 返回的链接与第一次相同的对象。所以这个对象已经改变了 [name] 属性。在第二个 block 的最后一行,我只想保存 [other] 文件,但 [other] 和 [name] 都将被更新。
解决这种情况的正确方法是什么?
最佳答案
这是设计使然。
实体管理器确保您始终为给定的 id 获取相同的实体。毕竟,这就是身份的含义。只能有一个 ID 为 1 的唯一用户。
如果要“刷新”数据库中的实体,EntityManager::refresh()会为你做的。从文档:
Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.
关于orm - 如何在 Doctrine 2 中丢弃对实体的未刷新更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750939/