如何使用Symfony和Doctrine Query Builder执行连接查询

时间:2013-08-21 12:15:14

标签: php sql symfony doctrine

我有两个通过1:1关系连接的实体,例如:MyEntity.idRelatedEntity 我想创建一个Doctrine查询,我可以根据MyEntity中某个列的值从RelatedEntity检索数据。这样的事情(当然不起作用):

$entity = $em
    ->getRepository('MyBundle:RelatedEntity')
    ->createQueryBuilder('e')
    ->leftJoin('MyBundle:RelatedEntity', 'r')
    ->where('r.foo = 1')
    ->getQuery()
    ->getResult();

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:17)

$entity = $em
    ->getRepository('MyBundle:MyEntity')
    ->createQueryBuilder('e')
    ->join('e.idRelatedEntity', 'r')
    ->where('r.foo = 1')
    ->getQuery()
    ->getResult();

此处左连接也没有意义(因为where子句会使其像内部连接一样工作)

答案 1 :(得分:14)

请注意,您应该在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();
}

然后在您的控制器/服务中使用它:

$manager = $this->getDoctrine()->getManager();
$results = $manager->getRepository(MyEntity::class)->getMyEntityWithRelatedEntity(1);