Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine: Cannot select entity through identification variables without choosing at least one root entity alias

I'm using the following code in the query builder, to select an average of score values, and the category entity to which that average belongs:

$queryBuilder = $this->createQueryBuilder('s')
    ->resetDQLPart('select')
    ->select('AVG(s.score) as score, partial c.{reviewCategoryID} as cat')
    ->setParameter('status', ReviewStatusType::ACCEPTED)
    ->join('s.review', 'r')
    ->join('s.category', 'c')
    ->where('r.campsite = :campsite')
    ->andWhere('r.status = :status')
    ->setParameter('campsite', $campsite)
    ->groupBy('c.reviewCategoryID');

$campsite is an entity to which a review belongs, while scores belong to a review, and scores have a category.

But when I try to execute this, i get the error

Error: Cannot select entity through identification variables without choosing at least one root entity alias.

When I debug and I check the root aliases, I see that 's' is defined, which is should be the root entity (Score).

Any idea what could be wrong?

like image 614
Michel Maas Avatar asked Jul 26 '13 09:07

Michel Maas


1 Answers

createQueryBuilder() can only take a parameter when it is called from the repository of the matching entity. In case you do not call it from this repository you should define a from method.

->from('YourMappingSpace:Campsite', 's')

Passing a parameter to createQueryBuilder() is for conveniance anyway. You can always define it manually. The function looks like this (Only inside the entity repository):

public function createQueryBuilder($alias)
{
    return $this->_em->createQueryBuilder()
        ->select($alias)
        ->from($this->_entityName, $alias);
}
like image 125
Flip Avatar answered Nov 14 '22 22:11

Flip