gpt4 book ai didi

php - Doctrine2 的 preUpdate 在 Symfony2 中缺少 PreUpdateEventArgs 参数

转载 作者:可可西里 更新时间:2023-10-31 23:53:02 26 4
gpt4 key购买 nike

preUpdate 事件的 Doctrine2 文档 says

This event has a powerful feature however, it is executed with a PreUpdateEventArgs instance, which contains a reference to the computed change-set of this entity. This means you have access to all the fields that have changed for this entity with their old and new value.

听起来很有用!所以我做什么:

/**
* Acme\TestBundle\Entity\Article
*
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
*/
class Article
{
// ...

/**
* @ORM\PreUpdate
*/
public function preUpdate(\Doctrine\ORM\Event\PreUpdateEventArgs $eventArgs)
{
if ( /* use $eventArgs here */ )

$this->updatedAt = new \DateTime();
}

// ...
}

但运气不好 - 没有传递任何参数:

Catchable Fatal Error: Argument 1 passed to
Acme\TestBundle\Entity\Article::preUpdate() must be an instance of
Doctrine\ORM\Event\PreUpdateEventArgs, none given, called in
...\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataInfo.php on line 1540 and defined in ...\src\Acme\TestBundle\Entity\Article.php line 163

我想这在 Symfony2 中必须以其他方式工作。我该怎么做?

最佳答案

您应该记得,使用 PreUpdateEventArgs 实例,您可以访问该实体的所有已更改的字段及其旧值和新值。但是在您的示例中, updatedAt 不会在该变更集中。如果您尝试设置 updatedAt 值,您应该会收到错误消息:“字段‘updatedAt’不是实体的有效字段”。因此,您可以更改 updateAt 字段,然后使用 UnitOfWork:recomputeSingleEntityChangeSet。示例:

public function preUpdate(PreUpdateEventArgs $args)
{
$entity = $args->getEntity();
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();

if ($entity instanceof Product)
{
$entity->setDiscount(123);

$uow->recomputeSingleEntityChangeSet(
$em->getClassMetadata("XXXBundle:Product"),
$entity
);
}
}

更多代码示例在我的博客文章中(在 russain:)):Update doctine entity in preUpdate event

关于php - Doctrine2 的 preUpdate 在 Symfony2 中缺少 PreUpdateEventArgs 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9140815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com