Php – Doctrine: No alias was set before invoking getRootAlias() error

doctrinedoctrine-ormPHPsymfony

My Original Query is:

Select * from user u
inner join company c
on u.company_id = c.id 
where u.id=2

And I made it as:

$em = $this->get('doctrine')->getEntityManager();
        $qb = $em->createQueryBuilder();

        $qb->select('u')
            ->from('TemplateManager\Bundle\DocumentGeneratorBundle\Entity\User u')
            ->innerjoin('u.company')
            ->where('u.id = ' . $id);
        $query = $qb->getQuery();
        $result = $query->getResult();

I get 500 with following details in Log:

[2016-09-27 12:06:34] request.INFO: Matched route
"templatemanager_documentgenerator_api_client_find" (parameters:
"_controller":
"TemplateManager\Bundle\DocumentGeneratorBundle\Controller\API\ClientController::findAction",
"id": "2", "_route":
"templatemanager_documentgenerator_api_client_find") [] []

> [2016-09-27 12:06:34] security.DEBUG: Read SecurityContext from the
session [] []

> [2016-09-27 12:06:34] security.DEBUG: Reloading user from user
provider. [] []

> [2016-09-27 12:06:34] security.DEBUG: Username "admin" was reloaded
from user provider. [] []

> [2016-09-27 12:06:34] request.CRITICAL: Uncaught PHP Exception
RuntimeException: "No alias was set before invoking getRootAlias()."
at //myproject//vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php
line 423 {"exception":"[object] (RuntimeException(code: 0): No alias
was set before invoking getRootAlias(). at
//myproject//vendor/doctrine/orm/lib/Doctrine/ORM/QueryBuilder.php:423)"}
[]

> [2016-09-27 12:06:34] security.DEBUG: Write SecurityContext in the
session [] []

Best Answer

try this add the alias on $em->createQueryBuilder();

$em->createQueryBuilder('u');

by the way prepare your query to avoid sql injection

$qb->select('u')
  ->from('User', 'u')
  ->where('u.id = ?1')
  ->orderBy('u.name', 'ASC')
  ->setParameter(1, 100);

On my own project I tried this and it works well:

$em = $this->get('doctrine')->getEntityManager();

$qb = $em->createQueryBuilder('u');

$qb->select('u')
        ->from('INSIDE\Bundle\AdminBundle\Entity\TAdminUser', 'u')
        ->innerJoin('u.idUser' , 'myalias')
        ->where('u.idAdminUser = 2');

$query = $qb->getQuery();
$result = $query->getResult();

idUser is another table not an id we had migration problems :)

Related Topic