Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - Notice: Undefined offset: 0 due to a custom Query

I have this error :

"Notice: Undefined offset: 0 in C:\wamp\www\Videotheque\vendor\doctrine\lib\Doctrine\ORM\QueryBuilder.php line 240"

I am creating a video collection online. There are 2 entities : Film and Genre. In my GenRerepositorymethod, I tried to redefine the function findAll() to the number of films associated to a genre.

This is the function :

public function myFindAll()
{
    $genres = $this->_em->createQueryBuilder('g')
                        // leftJoin because I need all the genre
                        ->leftJoin('g.films', 'f')
                        ->addSelect('COUNT(f)')
                        ->groupBy('g')
                        ->getQuery()
                        ->getArrayResult();
    // $genres contains all the genres and the associated movies
    return ($genres);
}
like image 585
Adrien G Avatar asked Aug 01 '12 09:08

Adrien G


2 Answers

The Repository class provides the method for creating a QueryBuilder already configured for the entity so we can directly put :

$this->createQueryBuilder('g')
like image 93
Adrien G Avatar answered Oct 14 '22 13:10

Adrien G


Found this issue myself and wanted to post my solution. Since you are creating a queryBuilder off of the EntityManager instead of an EntityRepository you need a from statement. The error arises when there is no from statement or if the from statement is out of order (the from needs to come before any join for it to be happy). The EntityRepository takes care of this for you when using it.

public function myFindAll()
{
    $genres = $this->_em->createQueryBuilder('g')
                        //from statement here
                        ->from('GenreEntityClass', 'g')
                        // leftJoin because I need all the genre
                        ->leftJoin('g.films', 'f')
                        ->addSelect('COUNT(f)')
                        ->groupBy('g')
                        ->getQuery()
                        ->getArrayResult();
    // $genres contains all the genres and the associated movies
    return ($genres);
}
like image 23
Matt R. Avatar answered Oct 14 '22 14:10

Matt R.