我有两个通过1:1关系连接的实体,例如:MyEntity.idRelatedEntity
我想创建一个Doctrine查询,我可以根据MyEntity
中某个列的值从RelatedEntity
检索数据。这样的事情(当然不起作用):
$entity = $em
->getRepository('MyBundle:RelatedEntity')
->createQueryBuilder('e')
->leftJoin('MyBundle:RelatedEntity', 'r')
->where('r.foo = 1')
->getQuery()
->getResult();
非常感谢任何帮助:)
答案 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);