Cze*_*ogy 3 php symfony doctrine-orm
关于preUpdate事件的Doctrine2文档说
此事件具有强大的功能,但它使用
PreUpdateEventArgs实例执行,该实例包含对此实体的计算更改集的引用.这意味着您可以使用旧值和新值访问已为此实体更改的所有字段.
听起来很有用!所以我做了什么:
/**
* 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();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
但没有运气 - 没有参数传递:
可捕获的致命错误:传递给的参数1
Acme\TestBundle\Entity\Article::preUpdate()必须是一个实例
Doctrine\ORM\Event\PreUpdateEventArgs,没有给定,在
...\vendor\doctrine\lib\Doctrine\ORM\Mapping\ClassMetadataInfo.php第1540行调用并在...\src\Acme\TestBundle\Entity\Article.php第163 行中定义
我想这必须在Symfony2中以其他方式工作.我该怎么做?
小智 16
您应该记住,对于PreUpdateEventArgs实例,您可以访问具有旧实体和新值的此实体已更改的所有字段.但在你的例子中,updatedAt不会在那个变更集上.如果您尝试设置updatedAt值,则应该收到错误:"字段'updated't'不是实体的有效字段".因此,您可以更改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
);
}
}
Run Code Online (Sandbox Code Playgroud)
我的博客文章中的更多代码示例(在russain :)):更新preUpdate事件中的doctine实体