Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony DQL query in repository

I have a problem with a query. I'm building application on Symfony 2.7 and I want to make a query in the repository, but when I make it throws exception saying:

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

Here is the code in the repository:

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;
}

}

But when I return the code in the Controller method it work.

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

Why this code do not work with Doctrine Entity manager in the repository?

like image 288
George Plamenov Georgiev Avatar asked Jan 09 '16 14:01

George Plamenov Georgiev


1 Answers

You are getting this error because you're calling a non-existent repository method getDoctrine(). Try this:

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;
    }    
}
like image 50
Anas EL KORCHI Avatar answered Sep 30 '22 12:09

Anas EL KORCHI