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查询,我可以根据RelatedEntity中某个列的值从MyEntity中检索数据。像这样的东西(它当然不起作用):
$entity = $em
->getRepository('MyBundle:RelatedEntity')
->createQueryBuilder('e')
->leftJoin('MyBundle:RelatedEntity', 'r')
->where('r.foo = 1')
->getQuery()
->getResult();
Any help would be much appreciated :)
任何帮助将非常感激 :)
2 个解决方案
#1
17
$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子句会使它像内部连接一样工作)
#2
14
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);
#1
17
$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子句会使它像内部连接一样工作)
#2
14
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);