在链配置的命名空间 XXX 中找不到 class 'Doctrine\ORM\EntityManager'

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured namespaces XXX

我已经阅读了有关此问题的其他问题,但尚未找到解决方案。

我收到以下错误消息:

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured >namespaces ZfcUser\Entity, Common\Entity, Employment\Entity, Intern\Entity, >Team\Entity, PurchaseRequest\Entity.

我有一个 HolidayEntity、HolidayController、HolidayService。

添加假期有效,但当我尝试删除假期时弹出错误。 我将假日 ID 从控制器传递到服务,然后它获取关联的对象并运行 doctrine 2 removeEntity 命令。

目前我不确定如何解决这个问题。

控制器代码:

public function deleteAction()
{
    $holidayId = $this->params()->fromRoute('id', 0);
    try {  
        $this->getServiceLocator()->get('holidayService')->removeHoliday($holidayId);
    } catch (Exception $e) {
        $this->flashMessenger()->addErrorMessage($e->getMessage() . '<br>' . $e->getTraceAsString());
    }
    return $this->redirect()->toRoute('holiday/list');
}

服务代码:

public function removeHoliday($holidayId)
{
    try{
    $holiday = $this->findOneHolidayById($holidayId);
    $this->removeEntity($holiday);
    } catch (Exception $e) {
        var_dump($e);
    }
}

protected function removeEntity($entity)
{
    $this->getEntityManager()->remove($entity);
    $this->getEntityManager()->flush();
}

代码在“$this->getEntityManager()->remove($entity)”方法中中断。

您遇到的错误与 Doctrine 无法找到名为 Doctrine\ORM\EntityManager 的实体有关,这显然是错误的。

我的猜测是您在某处(可能在 getEntityManager() 方法中)将实体管理器的实例传递给实体管理器。

例如

$entityManager = new EntityManager();
$entity = new EntityManager();
$entityManager->remove($entity);

@AlexP 的回答是正确的。具体来说,这是使用学说时常见的错误之一:

Repository.php

public function findBySomething($something)
{
    return $this->createQueryBuilder('e')
       ->where('e.something = :something')
       ->setParameter('something', $something);
}

其他地方

// WRONG USE CASE

$entity = $this->repository->findBySomething('foo');
$this->entityManager->remove($entity);

更正

$entity = $this->repository->findBySomething('foo')
    ->getQuery()
    ->getFirstResult();
$this->entityManager->remove($entity);