本文介绍了如何在Doctrine2中的PrePersist LifecycleCallback上访问旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Doctrine2中有一个实体,并在PrePersist中使用HasLivecycleCallbacks.通常,这可以正常工作,但是当我实体中的某些字段发生更改时,我只想更改版本.我有机会获得旧的价值观吗?还是只是已更改的键?

I have an entity in Doctrine2 and use the HasLivecycleCallbacks with PrePersist. In general this works fine, but I would like to change the version only, when certain fields in my entity change. Do I have a chance to get the old Values? Or just the keys that have been changed?

/**
 * @ORM\HasLifecycleCallbacks
 */
class Person {


    /**
     * @PrePersist
     * @PreUpdate
     */
    public function increaseVersion() {


            if ( $this->version == null ) {
                $this->version = 0;
            }
            // only do this, when a certain attribute changed
            $this->version++;
    }
}

推荐答案

这取决于我们在讨论哪个LifecycleEvent. PrePersist和PreUpdate是不同的事件.

It depends on which LifecycleEvent we are talking about. PrePersist and PreUpdate are different events.

PreUpdate .这将为您提供 PreUpdateEventArgs 对象,它是扩展的LifecycleEventArgs对象.这将允许您查询更改的字段,并允许您访问旧值和新值:

PreUpdate is fired before an Entity is, well, updated. This will give you a PreUpdateEventArgs object, which is an extended LifecycleEventArgs object. This will allow you to query for changed fields and give you access to the old and new value:

if ($event->hasChangedField('foo')) {
    $oldValue = $event->getOldValue('foo');
    $newValue = $event->getNewValue('foo');
}

您还可以通过getEntityChangeSet()获取所有更改的字段值,这将为您提供如下数组:

You could also get all the changed field values through getEntityChangeSet(), which would give you an array like this:

array(
    'foo' => array(
        0 => 'oldValue',
        1 => 'newValue'
    ),
    // more changed fields (if any) …
)

另一方面,

PrePersist 假定使用新的实体(请考虑插入新行).在PrePersist中,您将获得 LifecycleEventArgs 对象,该对象只能访问Entity和 EntityManager .从理论上讲,您可以访问 UnitOfWork (可跟踪实体的所有更改),因此您可以尝试

PrePersist, on the other hand, assumes a fresh Entity (think insert new row). In PrePersist, you'll get a LifecycleEventArgs object which only has access to the Entity and the EntityManager. In theory, you can get access to the UnitOfWork (which keeps track of all the changes to Entities) through the EntityManager, so you could try to do

$changeSet = $event->getEntityManager()->getUnitOfWork()->getEntityChangeSet(
    $event->getEntity()
);

获取要保留的实体的更改.然后,您可以检查此数组以查找更改的字段.但是,由于我们在谈论插入而不是更新,因此我假设所有字段都将被视为已更改",并且旧值可能全部为null.我不确定,这是否可以根据您的需要进行操作.

to get the changes for the to be persisted Entity. You could then check this array for changed fields. However, since we are talking about an insert and not an update, I assume all fields wil be considered "changed" and the old values will likely be all null. I am not sure, this will work as you need it.

更多参考: http://docs.doctrine- project.org/en/2.0.x/reference/events.html

这篇关于如何在Doctrine2中的PrePersist LifecycleCallback上访问旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 23:40