I am using cakephp 3. Here I need sum a field, I already done it.
//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);
}
Here I have used first(), but why still it's returning an object. Is it possible to get direct sum or array. Here I don't want to use foreach.
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With