在原则侦听器中插入元素 [英] Inserting element in doctrine listener

查看:90
本文介绍了在原则侦听器中插入元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设置了一个在不同的数据库操作上触发的教条侦听器,并创建一个日志实体并将其插入数据库。

I have setup a doctrine listener which is fired on different database actions and creates a log entity and insert it into the database.

class FOO { 
 // [...]
 public function onFlush(OnFlushEventArgs $args)
 {
     foreach ($args->getEntityManager()->getUnitOfWork()->getScheduledEntityUpdates() as $entity) {
                $this->createLog('edit', $entity);
     }
 }


 private function createLog($action, $entity)
 {
        if ($entity instanceof Log) {
            return;
        }
        $log = new Log;
        $log->setAction($action);
        $log->setTime(new \DateTime);
        $log->setForeignId($entity->getId());
        $log->setUser($this->getUser());
        $t            = explode('\\', get_class($entity));
        $entity_class = strtolower(end($t));
        $log->setEntity($entity_class);
        $this->getEntityManager()->persist($log);
  }
// [...]
}

当我更新一个对象时,我收到以下错误:

When I update an object, I get the following error:


SQLSTATE [HY093]:参数号无效:没有参数被绑定

SQLSTATE[HY093]: Invalid parameter number: no parameters were bound

在分析器中我看到这个查询:

In the profiler I see this query:


INSERT INTO vvg_logs(action,entity,foreign_id,user_id,time)VALUES(?,?,?,?,?)

INSERT INTO vvg_logs (action, entity, foreign_id, user_id, time) VALUES (?, ?, ?, ?, ?)

参数:{}

我如何解决这个问题?

更新
这是连接到此问题的新主题: LINK

推荐答案

因为当 onFlush 被调用时,所有更改都已经计算好了如果您更改实体或创建新实体,则需要刷新它们。

Because when onFlush is called, all changes are already calculated and you need to refresh them if you change your entity or create a new entity.

$em = $this->getEntityManager();
$uow = $em->getUnitOfWork();
$logMetadata = $em->getClassMetadata('Your\LogClass');
...
$em->persist($log);
$uow->computeChangeSet($logMetadata, $log);






对于postPersist:

$em = $this->getEntityManager();
$uow = $em->getUnitOfWork();
$log = new Log;
...

$logMetadata = $em->getClassMetadata('Your\LogClass');
$className = $logMetadata->name;
$persister = $this->getEntityPersister($className);
$persister->addInsert($log);
$uow->computeChangeSet($classMeta, $logEntry);
$postInsertIds = $persister->executeInserts();

if ($postInsertIds) {
    foreach ($postInsertIds as $id => $entity) {
        $idField = $logMetadata->identifier[0];
        $logMetadata->reflFields[$idField]->setValue($entity, $id);
        $this->addToIdentityMap($entity);
    }
}

这篇关于在原则侦听器中插入元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆