1

I want to convert the sql query below to doctrine query in symfony.

select p.name,p.id,sum(t.amount) as bal from transactions t right join processors p on t.processor_id=p.id where user_id=18 or user_id is null group by p.id

The above code fetches balance from transactions table by summing up amounts of each transaction for a user for each processor.

Result:

Processor1 --------- 43

Processor2 --------- 12

Processor3 --------- NULL

Processor4 --------- NULL

Processor5 --------- NULL

The query i tried with dql is:

$sql = $procRepo->createQueryBuilder('t');
        $sql->select('p.name');
        $sql->leftJoin('t.processorId','p');
        $sql->addSelect('sum(t.amount) as bal');
        $sql->groupBy('p.id');
        $sql->orderBy('p.name')->getQuery()->getResult();

Result:

Processor1 --------- 43

Processor2 --------- 12

So my problem is i also want to get the NULL rows.

Note: I am using Symfony 3

Can anybody help?

AllexOne
  • 13
  • 4

1 Answers1

-1

You needs to invert the join statement to gets all processors:

$sql = $procRepo->createQueryBuilder('p');
$sql->select('p.name', 'sum(t.amount) as bal');
$sql->leftJoin('p.transaction', 't');
$sql->groupBy('p.id');
$result = $sql->orderBy('p.name')->getQuery()->getResult();

This query must be made in your ProcessorRepository.

yceruto
  • 9,230
  • 5
  • 38
  • 65
  • I got this when i did that. `[Semantical Error] line 0, col 80 near 't GROUP BY p.id': Error: Class ModelBundle\Entity\Processor has no association named transaction` Do i need to add any mapping info to processors entity – AllexOne Aug 26 '16 at 16:52
  • Yes, which is not the exact name of the relationship, please, fix that in your real code. – yceruto Aug 26 '16 at 16:57
  • Actually i have two entities: Processor and Transaction
    There is a manyToOne mapping for column "processor_id" in transaction. Processor entity does not have any mapping to Transaction
    – AllexOne Aug 26 '16 at 16:59
  • well, test in you original query using `rightJoin` statement – yceruto Aug 26 '16 at 17:32
  • it worked, just needed an inversedBy and mappedBy combo :) Thanks so much! – AllexOne Aug 26 '16 at 19:33