微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在doctrine listener中插入元素

我已经设置了一个doctrine监听器,它在不同的数据库操作上触发,并创建一个日志实体并将其插入到数据库中.

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);
  }
// [...]
}

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

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

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

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

Parameters: { }

我怎么能解决这个问题?

UPDATE
这是我的新主题,连接到这个问题:LINK

解决方法:

因为调用onFlush时,所有更改都已计算,如果更改实体或创建新实体,则需要刷新它们.

$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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐