Search code examples
cakephpcakephp-3.xsql-function

How to use Sum in cakephp 3.8 querybuilder?


I have this simple code and I want to know how to use the cakephp 3.8 querybuilder to make a query and then how to fetch it..

SELECT sum(quantity) as quant from carts WHERE user_id = 7;

I am using this query:

$quantity = $this->Carts
    ->find()
    ->select([
        'quant' => $quantity->func()->sum('quantity')
    ])
    ->where([
        'user_id' => $this->Auth->user('id')
    ])
    ->toArray();

Is this right?

I am getting this Error- Call to a member function func() on null


Solution

  • The $quantity variable doesn't exist until after the query builder returns from the toArray() call, so you can't use it earlier in the select() call, and even afterwards the return value isn't a query builder instance anymore, but an array of results, as that is what toArray() will return.

    Either store a reference to the query builder before invoking select(), like:

    $quantityQuery = $this->Carts->find();
    $quantity = $quantityQuery 
        ->select([
            'quant' => $quantityQuery->func()->sum('quantity')
        ])
        //...
    

    or pass a callable to select(), it will retrieve the query instance as an argument:

    $quantity = $this->Carts
        ->find()
        ->select(function (\Cake\ORM\Query $query) {
            return [
                'quant' => $query->func()->sum('quantity')
            ];
        })
        //...
    

    See also