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):
$entity = $em
->getRepository('MyBundle:RelatedEntity')
->createQueryBuilder('e')
->leftJoin('MyBundle:RelatedEntity', 'r')
->where('r.foo = 1')
->getQuery()
->getResult();
Any help would be much appreciated :)
$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)
Note that you should write this query in your 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);