存储库中的 Symfony DQL 查询

Symfony DQL query in repository

我的查询有问题。我正在 Symfony 2.7 上构建应用程序,我想在存储库中进行查询,但是当我进行查询时抛出异常说:

Undefined method 'getDoctrine'. The method name must start with either findBy or findOneBy!

这是存储库中的代码:

namespace George\ObjectsBundle\Entity;

/**
 * ObjectRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ObjectRepository extends \Doctrine\ORM\EntityRepository
{
public function getOggallery()
{
    $em = $this->getDoctrine()->getManager();
    $query = $this->createQuery("SELECT o, a FROM George\ObjectsBundle\Entity\Object  o JOIN o.ogallery a WHERE a.ord = 0");
    $objects = $query->getResult();

    return $objects;
}

}

但是当我 return Controller 方法中的代码有效时。

 $query = $em->createQuery("SELECT o, a FROM George\ObjectsBundle\Entity\Object  o JOIN o.galleries a WHERE a.ord = 0");
 $objects = $query->getResult();

为什么此代码不能与存储库中的 Doctrine 实体管理器一起使用?

您收到此错误是因为您正在调用 non-existent 存储库方法 getDoctrine()。试试这个:

class ObjectRepository extends \Doctrine\ORM\EntityRepository
{
    public function getOggallery()
    {
        $em = $this->getEntityManager();
        $query = $em->createQuery("SELECT o, a FROM George\ObjectsBundle\Entity\Object  o JOIN o.ogallery a WHERE a.ord = 0");
        $objects = $query->getResult();

        return $objects;
    }    
}