Cakephp 3:在不使用foreach的情况下对单个字段求和

时间:2016-09-30 04:14:00

标签: cakephp cakephp-3.0

我正在使用cakephp 3.在这里我需要求和一个字段,我已经完成了。

//mobile recharge total balance
$user_balance = $this->Users->find();
$user_balance
->select(['sum' => $user_balance->func()->sum('Users.balance')])
->first();
foreach ($user_balance as $balance) {
    $this->set("user_balance", $balance->sum);
}

这里我使用了first(),但为什么还要返回一个对象。是否可以获得直接求和或数组。在这里,我不想使用foreach。

1 个答案:

答案 0 :(得分:8)

$query = $this->Models->find('all'); //fetch the record

$res = $query->select(['total_sum' =>$query->func()->sum('the_field_you_need')])->first(); //perform the sum operation 
$total = $res->total_sum; your total sum result
$user_balance = $this->Users->find();
$res =$user_balance->select(['sum' => $user_balance->func()->sum('Users.balance')])->first();
$total = $res->sum; //your total sum result