Aggregate SUM with Doctrine2 and QueryBuilder

jsf picture jsf · Jun 24, 2013 · Viewed 8.3k times · Source

in my repository class I have this, but the query is not working.

 public function getResultsByName($page, $resultsCount, array $request_arr){     
 $qb = $this->createQueryBuilder('xx'); 
 $qb->addSelect('SUM(xx.quantity) as total')
    ->leftJoin('xx.reception', 'x')
    ->addSelect('x')
    ->leftJoin('x.purchase', 'p')
    ->addSelect('p')
    ->leftJoin('p.provider', 'pr')
    ->addSelect('pr')
    ->where('pr.id = :company_id')
    ->setParameter('company_id', $request_arr['company_id']);

 $query = $qb->getQuery(); 

 return parent::getPaginator($query, $page, $resultsCount); }

The error is appearing in my twig template this is the important chunk of it

    {% for result in results %}
<tr>
    <td>{{result.reception.id}}</td>
    <td>{{result.reception.date|date('d-m-Y')}}</td>
    <td>{{result.reception.purchase.id}}</td>
    <td>{{result.reception.purchase.provider.name|upper}} [{{result.reception.purchase.provider.id}}]</td>
    <td>{{result.purchaseProduct.name |upper}} [{{result.purchaseProduct.productCode |upper}}]</td>
    <td>{{result.purchasePrice}}</td>
    <td>{{result.quantity}}</td>
    <td></td>
    <td>{{result.quantityStock}}</td>
</tr>   
{% endfor %}

Answer

Paul Andrieux picture Paul Andrieux · Jun 24, 2013

as you have two selects on your query, your result object is an array of this kind:

array(
    'total' => $total,
    'xx' => array(
        'reception' => $reception,
        'quantityStock' => $quantityStock,
        [...]
    ) 
);

To access your properties in twig, you have to access it like that:

{{result.xx.reception}}
{{result.total}}