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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply