php 如何使用 Symfony 和 Doctrine Query Builder 执行连接查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18357159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to perform a join query using Symfony and Doctrine Query Builder
提问by viarnes
I have two entities which are connected through a 1:1 relationship, e.g: MyEntity.idRelatedEntity
I want to create a Doctrine query where I can retrieve data from MyEntity
depending on a value from a certain column in RelatedEntity
. Something like this (it doesn't work of course):
我有两个通过 1:1 关系连接的实体,例如:MyEntity.idRelatedEntity
我想创建一个 Doctrine 查询,我可以MyEntity
根据RelatedEntity
. 像这样的东西(它当然不起作用):
$entity = $em
->getRepository('MyBundle:RelatedEntity')
->createQueryBuilder('e')
->leftJoin('MyBundle:RelatedEntity', 'r')
->where('r.foo = 1')
->getQuery()
->getResult();
Any help would be much appreciated :)
任何帮助将非常感激 :)
回答by Uriziel
$entity = $em
->getRepository('MyBundle:MyEntity')
->createQueryBuilder('e')
->join('e.idRelatedEntity', 'r')
->where('r.foo = 1')
->getQuery()
->getResult();
Also left join makes no sense here (because of where clause that will make it work like inner join)
左连接在这里也没有意义(因为 where 子句将使它像内连接一样工作)
回答by sf_tristanb
Note that you should write this query in your MyEntityRepository
请注意,您应该在您的 MyEntityRepository
public function getMyEntityWithRelatedEntity($parameter)
{
$query = $this->createQueryBuilder('e')
->addSelect('r') // to make Doctrine actually use the join
->leftJoin('e.relatedEntity', 'r')
->where('r.foo = :parameter')
->setParameter('parameter', $parameter)
->getQuery();
return $query->getResult();
}
And then use it in your controller/service :
然后在您的控制器/服务中使用它:
$manager = $this->getDoctrine()->getManager();
$results = $manager->getRepository(MyEntity::class)->getMyEntityWithRelatedEntity(1);