rococo polkadot bandit rococo polkadot bandit - 12 days ago 6
PHP Question

Custom repository problems with Symfony2 - Notice: Undefined offset: 0

I'm trying to move my query into a custom repository class. Here is what I've got so far

class MovieRepository extends EntityRepository
{
public function showMovie($movie)
{
$em = $this->getEntityManager();

$qb = $em->createQueryBuilder('m');

$query = $qb->select('m.title', 'm.img', 'u.username')
->where('m.title = :movie')
->leftJoin('m.user', 'u')
->setParameter('movie', $movie)
->getQuery();

return $query->getSingleResult();
}
}


I use it like this in my controller:

$em = $this->getDoctrine()->getManager();
$result = $em->getRepository('AMovieBundle:Movie')->showMovie($movie);


I did put the @ORM\Entity(repositoryClass="A\MovieBundle\Entity\MovieRepository") in my entity and the namespaces and folders are correct, and my relations from the movie to the user is correct as this worked before, when I had the query in the controller.

The primary error I keep getting is this:


Notice: Undefined offset: 0 in /Applications/MAMP/htdocs/symfony2test/vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php line 271


Line 271 in the query builder is this:

public function getRootAlias()
{
$aliases = $this->getRootAliases();
return $aliases[0];
}


I have no idea where to go from here and any help would be greatly appreciated.

Answer

A quick tip, the function getRootAlias() returns the alias created for the query, which is in your case "m".

If i make an educated guess i'll try this (note the select syntax) :

$query = $qb->select('m.title, m.img, u.username')
            ->where('m.title = :movie')
            ->leftJoin('m.user', 'u')
            ->setParameter('movie', $movie)
            ->getQuery();

You are already inside an EntityRepository, you don't need to call $this->getEntityManager().

Just do : $qb = $this->createQueryBuilder('m');

That should fix your problem.