How to perform a join query using Symfony and Doct

2019-01-27 17:15发布

问题:

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 :)

回答1:

$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)



回答2:

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);