We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

sum() and average() function default value feature

sum() and average() function on Phalcon\Mvc\Model, not return value if not matched any results like following query:

$transactions_today = Transactions::sum(
    [
        'column'        => 'total',
        "conditions"    => "status = :status: AND DATE(created) >= :start_date: AND DATE(created) <= :end_date:",
        "bind"          => [
                            'status' => true,
                            'start_date' => date('Y-m-d'), 
                            'end_date' => date('Y-m-d')
                        ]
    ]
);

Is there any feature return default value like that?

'defaultValue' => 0
edited Nov '17

I don't think there is 'defaultvalue' option, someone correct me if im wrong! Here is a simple solution. The aggregation functions return NULL when no results match the criteria.

$avgProductPrice = \Models\ProductVariants::average([
    'column' => 'price',
    'conditions' => 'stock > 12123'
]) ?? 0;

OR less hacky version:

$aggregation = \Models\ProductVariants::average([
    'column' => 'price',
    'conditions' => 'stock > 12123'
]);
$avgProductPrice = $aggregation ?? 0;


58.1k
edited Nov '17

I'm using already like that :)) But this is not professional solution =D

At the same time this question is my suggestion to specify the feature @phalcon

What's a problem with:

$transactions_today = (int)Transactions::sum(
    [
        'column'        => 'total',
        "conditions"    => "status = :status: AND DATE(created) >= :start_date: AND DATE(created) <= :end_date:",
        "bind"          => [
                            'status' => true,
                            'start_date' => date('Y-m-d'), 
                            'end_date' => date('Y-m-d')
                        ]
    ]
);
edited Nov '17

What else could you have as default value besides 0? I dont see how the concept of average and sum could have a default value. Returning NULL actually has information about your database; namely, the requested rows with those parameters do not exist. I have code which depends on that fact.

PHP is also untyped (go ahead, stone me php7.1 users!), why not just cast it as int and it will be 0.