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

Michel Maas picture Michel Maas · Jul 26, 2013 · Viewed 37.1k times · Source

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?

Answer

Flip picture Flip · Aug 4, 2013

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