简体   繁体   中英

How to write nested select sql query with doctrine query builder?

My query looks like

SELECT 
    COUNT(*) as cnt, ROUND(SUM(cost),2) as cost
FROM 
    (SELECT ROUND(SUM(cost),2) as cost FROM accounts LEFT JOIN earnings ON earnings.id = accounts.id WHERE earnings.date >= ? GROUP BY earnings.id) src;

How to write it using $querybuilder from Doctrine?

I have tried:

        $qb = $this->em->getConnection()->createQueryBuilder();
        $qb->select('COUNT(*) as cnt, ROUND(SUM(cost),2) as cost');
        $qb->from(
            $qb->select('SELECT ROUND(SUM(cost),2) as cost')
                ->from('accounts')
                ->leftJoin('accounts', 'earnings', 'earnings', 'earnings.id = accounts.id')
                ->where('earnings.date >= :date')->setParameter(':date', $dto->getFromSqlFormat())
                ->groupBy('earnings.id')
        );

But it is not working and I am getting error:

Warning: Illegal offset type

It looks like you need a total count of accounts and their sum of total cost from earnings table If so then i guess you can simplify your original query as

SELECT COUNT(DISTINCT a.id) cnt,
       ROUND(SUM(e.cost),2) as cost 
FROM accounts a
LEFT JOIN e ON e.id = a.id
WHERE e.date >= ?

No need for group by if you want a scalar result

In DQL it would be as

SELECT COUNT(DISTINCT a.id) cnt,
       SUM(e.cost) as cost 
FROM AppBundle\Entity\Account a 
LEFT JOIN a.earnings e
WHERE e.date >= ?

In query builder it would look like

$this->createQueryBuilder('a')
    ->select('count(distinct a.id) as cnt, sum(e.cost) as cost')
    ->from('AppBundle\Entity\Account','a')
    ->leftJoin('a.earnings', 'e')
    ->where('e.date = :date')
    ->setParameter('date', $date)
    ->getQuery();
    

You can always format your end result from your codebase so I have removed round from query builder and DQL

Prior to above make sure you have defined proper relation in your Account entity that points to Earning entity (one to many /many to many) otherwise this won't help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM