Rishu
Rishu

Reputation: 97

SUM query in cakephp 3 not working

I am trying to add the data of same field and want to return a result i used the following query:

$total = $this->Details->find('all', array(
    'fields' => array('sum(Details.total_downtime+ Details.total_downtime)'), 
    'conditions' => array('Details.site_id' => $id)
));    
print_r($total->toArray());
exit;

And I am getting the following result:

Array ( 
    [0] => App\Model\Entity\Detail Object ( 
        [displayField] => username 
        [_accessible:protected] => Array ( 
            [*] => 1 
            [id] => 1 
            [site_id] => 1 
            [uptime] => 1 
            [downtime] => 1 
        ) 
        [_properties:protected] => Array ( 
             [sum(Details] => Array ( [total_downtime+ Details] => 4 ) 
        ) 
        [_original:protected] => Array ( ) 
        [_hidden:protected] => Array ( ) 
        [_virtual:protected] => Array ( ) 
        [_className:protected] => App\Model\Entity\Detail [_dirty:protected] => Array ( ) 
        [_new:protected] => 
        [_errors:protected] => Array ( ) 
        [_registryAlias:protected] => Details 
    ) 
)

Where can I find my sum?

Upvotes: 3

Views: 7811

Answers (3)

user7329706
user7329706

Reputation: 11

Try this:

$Details = this->Details->find()->select(['sum'=>'SUM(Details.total_downtime)'])->where(['Details.site_id' => $id])->toArray();

Upvotes: 0

Faisal
Faisal

Reputation: 4765

You can do this collection object like below:

$Details = $this->Details->find();
$Details = $Details->where(['Details.site_id' => $id]);
$sumOftotal_downtime =  $Details->sumOf('Details.total_downtime');

Cookbook Reference

Upvotes: 2

makallio85
makallio85

Reputation: 1356

I guess you are trying to achieve something like this?

$query = $Details->find(); 
$query
    ->select(['sum' => $query->func()->sum('Details.total_downtime')])
    ->where(['Details.site_id' => $id])
    ->toArray();

Upvotes: 6

Related Questions