Search code examples
symfonydocumentquery-builderdql

How to sum the contents of a document field with symfony query builder?


I am just trying to get the total value of one of the fields of my documents but it's not working. What am I missing?

@ProductRepository

public function countTotalValue()
    {
       return $this->createQueryBuilder('a')
        ->select('SUM(a.price)')
        ->getQuery()
        ->getSingleScalarResult()
    ;
    }

Solution

  • I discovered it!

    public function countTotalValue()
        {
            $array = $this->createQueryBuilder()
                ->select('price')
                ->hydrate(false)
                ->getQuery()
                ->execute()
                ->toArray()
                ;
    
            $array = array_column($array, 'price');
            return (array_sum($array));
    
        }
    

    It was returning a complex array, I had to stripe it before make the sum.