存储库中的Symfony DQL查询

Geo*_*iev 5 doctrine repository symfony

嗨,大家好,我有一个问题的问题.我正在Symfony 2.7上构建应用程序,我想在存储库中进行查询,但是当我使它抛出异常时说:

未定义的方法'getDoctrine'.方法名称必须以findBy或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;
}

}
Run Code Online (Sandbox Code Playgroud)

但是当我在Controller方法中返回代码时,它可以工作.

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

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

elk*_*nas 7

您收到此错误是因为您正在调用不存在的存储库方法getDoctrine().试试这个:

class ObjectRepository extends \Doctrine\ORM\EntityRepository
{
    public function getOggallery()
    {
        $em = $this->getEntityManager();
        $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;
    }    
}
Run Code Online (Sandbox Code Playgroud)

  • 它根本不需要`$ em`它已经绑定到QueryBuilder了 (3认同)
  • 它实际上是必需的,因为 EntityRepository 没有 createQuery 方法,EntityManager 有。所以这个例子应该是 $em->createQuery(...); 甚至 $this->_em->createQuery(...); (2认同)