SQL/Doctrine: getResult in leftJoin returns object

2019-04-29 19:24发布

问题:

I've got the following problem in a Symfony2/Doctrine-Environment:

A class a has a relation with class b, however this relation is not registered through ORM annotations or anything else, because the referenced table is variable. So I join in the following way:

$query = $this->createQueryBuilder('a')
        ->select('a')
        ->addSelect('b')
        ->leftJoin('My\Bundle\EntityBundle\Entity\OtherClass','b',\Doctrine\ORM\Query\Expr\Join::WITH,'a.referenceId=b.id')
        ->getQuery()->getResult($hydrationMode);

The resulting array now contains both objects of a and b (sort of like

array('a1', 'b1', 'a2', 'b2', .... )

). I could filter through it once again, however I feel this is not the way to go. I've tried different Hydration-Modes, but that didn't change anything.

Is there any way to return it, so the association is preserved?

By this I mean sth like the following:

array(array('a1', 'b1'), array('a2', 'b2'), ...)

?

回答1:

You can achieve this by using the standard ScalarHydrator:

$query = $this->createQueryBuilder('a')
    ->select('a')
    ->addSelect('b')
    ->leftJoin('My\Bundle\EntityBundle\Entity\OtherClass','b','WITH','a.referenceId=b.id')
    ->getQuery()
    ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);