5

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);
}
Adrien G
  • 1,086
  • 2
  • 14
  • 32

3 Answers3

6

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

$this->createQueryBuilder('g')
Adrien G
  • 1,086
  • 2
  • 14
  • 32
1

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);
}
Matt R.
  • 2,209
  • 1
  • 17
  • 19
0

Try this:

public function myFindAll()
{
    $qb = $this->_em->createQueryBuilder('g');
    $qb->leftJoin('g.films', 'f')
       ->select($qb->expr()->count('f')) // Use an expression
       ->groupBy('g.id')                 // Specify the field
    ;

    $genres = $qb->getQuery()->getArrayResult();

    // $genres contains all the genres and the associated movies
    return ($genres);
}
Florent
  • 12,310
  • 10
  • 49
  • 58