这取决于我们正在谈论哪个 LifecycleEvent。PrePersist 和 PreUpdate 是不同的事件。 https://stackoverflow.com/questions/14345630/symfony-preupdate-vs-prepersist
更新前在实体更新之前触发。这会给你一个PreUpdateEventArgs https://www.doctrine-project.org/api/orm/2.6/Doctrine/ORM/Event/PreUpdateEventArgs.html对象,它是一个扩展的LifecycleEventArgs
目的。这将允许您查询更改的字段并允许您访问旧值和新值:
if ($event->hasChangedField('foo')) {
$oldValue = $event->getOldValue('foo');
$newValue = $event->getNewValue('foo');
}
您还可以通过以下方式获取所有更改的字段值getEntityChangeSet()
,这会给你一个像这样的数组:
array(
'foo' => array(
0 => 'oldValue',
1 => 'newValue'
),
// more changed fields (if any) …
)
预坚持另一方面,假设一个新的实体(认为插入新行)。在 PrePersist 中,您将得到LifecycleEventArgs http://www.doctrine-project.org/api/orm/2.4/class-Doctrine.ORM.Event.LifecycleEventArgs.html对象只能访问实体和EntityManager http://www.doctrine-project.org/api/orm/2.4/class-Doctrine.ORM.EntityManager.html。理论上,您可以访问UnitOfWork http://www.doctrine-project.org/api/orm/2.4/class-Doctrine.ORM.UnitOfWork.html(它跟踪实体的所有更改)通过EntityManager
,所以你可以尝试这样做
$changeSet = $event->getEntityManager()->getUnitOfWork()->getEntityChangeSet(
$event->getEntity()
);
获取要持久化的实体的更改。然后您可以检查该数组是否有更改的字段。然而,由于我们讨论的是插入而不是更新,我假设所有字段都将被视为“已更改”,并且旧值可能全部为空。我不确定,这是否会根据您的需要起作用。
进一步参考:http://docs.doctrine-project.org/en/2.0.x/reference/events.html http://docs.doctrine-project.org/en/2.0.x/reference/events.html