我的原始查询是:
Select * from user u
inner join company c
on u.company_id = c.id
where u.id=2
我做到了:
$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();
我在日志中获得500以下的详细信息:
[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 [] []
最佳答案 试试这个
在$em-> createQueryBuilder();上添加别名;
$em->createQueryBuilder('u');
顺便说一下准备你的查询以避免sql注入
$qb->select('u')
->from('User', 'u')
->where('u.id = ?1')
->orderBy('u.name', 'ASC')
->setParameter(1, 100);
在我自己的项目中,我试过这个并且效果很好:
$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是另一个表不是我们有迁移问题的id 🙂