gpt4 book ai didi

doctrine-orm - 学说 2 : preFlush getScheduledEntityInsertions() works but not getScheduledEntityUpdates()

转载 作者:行者123 更新时间:2023-12-03 20:17:37 31 4
gpt4 key购买 nike

我有一些具有抽象类的实体:EntityDated 这意味着该实体包含 4 个公共(public)字段:createdupdated创建者更新者。我想在创建实体时更新 4 数据,并在更新实体时更新“updated”和“updated_by”。

我做了一个调用我的监听器的服务:

public function preFlush(PreFlushEventArgs $eventArgs)
{
$token = $this->container->get('security.context')->getToken();
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();

// Inserts
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {

$entity->setCreated(new \Datetime());
$entity->setCreatedBy($token->getUser()->getUsername());
$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());

}
}

// Updates
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {

$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());

}
}
}

这仅适用于 INSERTS,不适用于 UPDATES(更改已保存,但更新和更新保持不变)。如果我调试 $uow->getScheduledEntityUpdates(),我发现它是空的。为什么不在此处管理更新的实体?

最佳答案

为了同时执行插入和更新,我必须更改两点:

  • 使用onFlush(),而不是preFlush()
  • 在每次更改后添加 recomputeSingleEntityChangeSet()

新代码:

public function onFlush(OnFlushEventArgs $eventArgs)
{

$token = $this->container->get('security.context')->getToken();
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();

// Inserts
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {

$entity->setCreated(new \Datetime());
$entity->setCreatedBy($token->getUser()->getUsername());
$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());

$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);

}
}

// Updates
foreach ($uow->getScheduledEntityUpdates() as $entity) {
if (is_subclass_of($entity, 'Kiwi\Bundle\TrainingBundle\Entity\EntityDated')) {

$entity->setUpdated(new \Datetime());
$entity->setUpdatedBy($token->getUser()->getUsername());

$meta = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($meta, $entity);

}
}

}

关于doctrine-orm - 学说 2 : preFlush getScheduledEntityInsertions() works but not getScheduledEntityUpdates(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26277625/

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