Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3 : Sum a single field without using foreach

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.

like image 641
Satu Sultana Avatar asked Feb 07 '23 00:02

Satu Sultana


1 Answers

$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
like image 171
sradha Avatar answered Mar 11 '23 00:03

sradha