我有一些抽象类的实体:EntityDated
这意味着该实体包含4个公共字段:created
,updated
,created_by
和updated_by
。我想在创建实体时更新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()
,我发现它是空的。为什么不在这里管理更新的实体?
答案 0 :(得分:6)
为了执行插入和更新,我不得不改变两点:
onFlush()
,而不是preFlush()
新代码:
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);
}
}
}