我已经设置了一个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: { }
我怎么能解决这个问题?
解决方法:
因为调用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);
}
}