Friday, December 31, 2021

[FIXED] SUM query in cakephp 3 not working

Issue

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?


Solution

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();


Answered By - makallio85

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.