我正在使用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。
答案 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