0

Im trying to Right join in symfony. I tried as described here Doctrine 2 - Outer join query and here Symfony - Using Outer Joins with Doctrine ORM .

$query = $em->getRepository('AppBundle:raports')->createQueryBuilder('r')
            ->select('r')
            ->leftJoin('r.requestRaports rr WITH rr.formId = :formId', false)
            ->setParameter('formId', $requestId->getFormId())
            ->getQuery();

it gives

 SELECT 
  r0_.id AS id_0, 
  r0_.adminComment AS adminComment_1, 
  r0_.addDate AS addDate_2, 
  r0_.submitDate AS submitDate_3, 
  r0_.statusId AS statusId_4, 
  r0_.userId AS userId_5, 
  r0_.requestId AS requestId_6, 
  r0_.requestRaports AS requestRaports_7 
FROM 
  raports r0_ 
  LEFT JOIN request_raports r1_ ON r0_.requestRaports = r1_.id 
  AND (r1_.formId = ?)

When i try

$query = $em->getRepository('AppBundle:raports')->createQueryBuilder('r')
            ->select('r')
            ->join('r.requestRaports rr WITH rr.formId = :formId', false)
            ->setParameter('formId', $requestId->getFormId())
            ->getQuery();

it looks like that

SELECT 
  r0_.id AS id_0, 
  r0_.adminComment AS adminComment_1, 
  r0_.addDate AS addDate_2, 
  r0_.submitDate AS submitDate_3, 
  r0_.statusId AS statusId_4, 
  r0_.userId AS userId_5, 
  r0_.requestId AS requestId_6, 
  r0_.requestRaports AS requestRaports_7 
FROM 
  raports r0_ 
  INNER JOIN request_raports r1_ ON r0_.requestRaports = r1_.id 
  AND (r1_.formId = ?)

But i want query like

SELECT * FROM raports r RIGHT JOIN request_raports rr ON r.requestRaports = rr.id

How to make right join work in doctrine2?

Community
  • 1
  • 1
hamzo
  • 195
  • 4
  • 14

1 Answers1

-1

You can ether use a LEFT JOIN and reversing your SQL like this

SELECT * FROM request_raports rr LEFT JOIN raports r ON r.requestRaports = rr.id

Or you can create your own "right join". If you look at leftJoin definition in doctrine, it's like :

leftJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null)
{
    $parentAlias = substr($join, 0, strpos($join, '.'));

    $rootAlias = $this->findRootAlias($alias, $parentAlias);

    $join = new Expr\Join(
        Expr\Join::LEFT_JOIN, $join, $alias, $conditionType, $condition, $indexBy
    );

    return $this->add('join', array($rootAlias => $join), true);
}

So, it may look like this :

$qb = $this->createQueryBuilder('b');

$rightJoin = new Expr\Join('RIGHT', 'r.requestRaports', 'rr', Expr\Join::WITH, 'rr.formId = :formId');
$qb
    ->select('r')
    ->add('join', ['r' => $rightJoin], true)
    ...

I have not tested this and don't know if its the best way to do it ...

Chuck Norris
  • 1,125
  • 1
  • 12
  • 28