Doctrine merge: DateTime field always updated(Doctrine 合并:DateTime 字段总是更新)
问题描述
我使用现有的 Id
创建了一个新实体,并且我想更新相关的数据库记录.
I create a new Entity with an existing Id
, and I want to update the related database record.
Doctrine 合并一直是我最好的朋友:识别是否有更改并生成正确的更新查询.
Doctrine merge has been my best friend: recognizes if there are changes and generates the correct update query.
假设 id=1 的元素已经存在于 db 中:如果名称与 'test' 不同,则 Doctrine 生成此查询:
Suppose that the element with the id=1 already exists in the db: if the name is different from 'test', Doctrine generates this query:
如果我再次运行上面的代码,Doctrine 会识别出没有任何变化,并且没有提交任何查询.
If I run again the code above, Doctrine recognizes that nothing is changed, and no query is committed.
但是... 当我设置 DateTime 字段时,Doctrine 认为它已更改并始终运行更新查询:
But... when I set a DateTime field, Doctrine consider it as changed and always runs the update query:
您知道避免这种无用更新的方法吗?谢谢!
Do you know a way to avoid this useless update? Thanks!
推荐答案
正如@Raymond 所说,这是预期的行为.
As said by @Raymond, it's the expected behavior.
很遗憾,但如果您的合并不依赖于 date
属性,则解决方法可能是在合并后设置日期,如下所示:
It's a pity, but if your merge doesn't depend on the date
property, a workaround could be to set the date after the merge like this:
更新
尝试后,唯一的选择似乎是检索合并的对象并通过再次刷新 EntityManager 来更新它.
After tried, the only alternative seems to retrieve the merged object and update it by flushing the EntityManager again.
您可以使用:
更新 2
我发现在合并后实现更新的更简洁的方法是重新合并实体,例如:
The cleaner way I found to achieve the update after the merge is re-merge the entity, e.g. :
但这并没有改变主要问题,也没有任何意义,因为您无法自己比较 DateTime
对象,$entity->getDate()
在调用 setDate
之前始终返回 null,即使在第一次合并之后也是如此.
But this doesn't change the main problem and doesn't really make sense because you cannot compare the DateTime
object by yourself, $entity->getDate()
return always null before calling setDate
, even after the first merge.
Doctrine 通过引用(散列)与 ===
比较对象,即使对象日期未更改,DateTime
的新实例也会导致更新.
Doctrine compare the objects by reference (hash) with ===
, also a new instance of DateTime
causes the update even if the object date is unchanged.
这是一个非常有问题的问题,可以通过使用 ==
作为比较运算符来解决,但是学说不能在不破坏它们的情况下为 DateTime
设置特定条件通用对象比较机制,涉及降低最常用功能之一的性能.
This is a really problematic issue that could be fixed by using ==
as comparison operator, but doctrine can't make a specific condition for DateTime
without breaking their generic object comparison mechanism, that involves to decrease performances of one of the most used feature.
这篇关于Doctrine 合并:DateTime 字段总是更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!