orm - 如何在 Doctrine 2 中丢弃对实体的未刷新更改?

标签 orm doctrine doctrine-orm

我长期使用基于 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/

相关文章:

java - 良好的 ORM Java 应用服务器

php - 在 Doctrine 2 实体上映射额外的行

c# - 您在数据应用程序中使用枚举吗?如何使用?

php - 服务层的数据访问和安全(Doctrine & ZF)

.net - T4 用于在 LLBLGen Pro 实体上生成 POCO?

codeigniter - 如何找出我正在运行的 Doctrine 版本?

php - Symfony 2.5 - 数据转换器和 View 转换器

php - 日期与 Doctrine2 和 Symfony2 的交集

php - 从异常中重新启动实体管理器

doctrine - Symfony2/Doctrine - 需要访问数据库的验证约束