Skip to content

Instantly share code, notes, and snippets.

@elvismdev
Last active November 3, 2021 10:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvismdev/5447ac515bcc776c3bff2fbfe936f560 to your computer and use it in GitHub Desktop.
Save elvismdev/5447ac515bcc776c3bff2fbfe936f560 to your computer and use it in GitHub Desktop.
SUM up all values from table column - Doctrine QueryBuilder.
<?php
// Sum all values from order_total column in completed orders, and return.
$qb = $em->createQueryBuilder();
$qb = $qb
->select( 'SUM(e.orderTotal) as totalRevenue' )
->from( '[Vendor]\[Package]\Entity\Orders', 'e' )
->where( $qb->expr()->andX(
$qb->expr()->eq( 'e.orderStatus', ':status' ),
// $qb->expr()->in( 'e.state', array( 'queued', 'confirmed' ) )
) )
->setParameter( 'status', 'completed' )
->getQuery()
;
$totalRevenue = $qb->getOneOrNullResult();
print_r( $totalRevenue );
@symfony4learner
Copy link

thanks!

@NBoulfroy
Copy link

Thx you !

@parijke
Copy link

parijke commented Nov 3, 2021

A slightly easier syntax would be:

    public function getAmountToBeInvoiced()
    {
        return $this->createQueryBuilder('t')
            ->select('(sum(t.quantity * t.amount)/100) as invoicableAmount')
            ->andWhere('t.invoicable = :true')
            ->andWhere('t.invoiced = :false')
            ->setParameter('true', true)
            ->setParameter('false', false)
            ->distinct()
            ->getQuery()
            ->getOneOrNullResult();
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment