Symfony2 $em->createQuery() 也选择移除的对象

Symfony2 $em->createQuery() also selects removed objects

前言:我的脚本有点复杂,所以我尝试将复杂性降低到一个简单的例子。

假设我们有一个实体 "company"。我们还有一个存储库功能,如下所示:

public function delete(){

    // get company-objects to delete
    [...]

    // delete some companies
    $this->getEntityManager()->remove($company1);
    $this->getEntityManager()->remove($company2);

    // do other things
    [...]

    // get companies via createQuery (I really need to do it via 
    // createQuery because of different reasons that would be too
    // complicated to explain for this problem)
    $query = $this->getEntityManager()
                    ->createQuery('
                        SELECT company
                        FROM MyOwnBundle:Company company
                        WHERE [...irrelevant...]
                    ');
    $companies = $query->getResult();
    dump($companies);
    exit;
}

问题:createQuery 还 select 删除了公司。

我的想法:

问题:如何在不删除公司的情况下通过 createQuery 获取公司?

您可以像下面这样包装您的代码,使您的整个过程都在一个事务中。这样您就可以在删除数据后立即刷新。

$this->getEntityManager()->transactional(function($em) {
   // put your code here
   // $em is instanceof EntityManager
});