Query creator retrieves data in cakephp 3.2

I use this code below to summarize the whole balance of my wallet.

$query = $this->Wallets->find();
$query->select([
    'count' => $query->func()->count('id'), 
    'total_price' => $query->func()->sum('amount')
])
->where(['status' => 4, 'user_id' => $user_id]);
pj($query);
echo $query->total_price;
exit;

out put of pj($query);

[
    {
        "count": 2,
        "total_price": 700
    }
]

Here I tried to get a separate individual value using the following query

echo $query->total_price;

I do not understand. What is the correct syntax, plz suggest me. Thanx.

0
source share
2 answers
$query = $this->Wallets->find();
$query->select([
    'count' => $query->func()->count('id'), 
    'total_price' => $query->func()->sum('amount')
])
->where(['status' => 4, 'user_id' => $user_id]);
debug($query);

// loop your results
foreach($query as $result){
   echo $result->total_price;
}

// or
$query->toArray();
echo $query[0]->total_price;
echo $query[1]->total_price;
...
exit;
+1
source

add first()to your request see manual

$query->select([
    'count' => $query->func()->count('id'), 
    'total_price' => $query->func()->sum('amount')
])
->where(['status' => 4, 'user_id' => $user_id]);

$wallet = $query->first();

debug($wallet);

debug($wallet->total_price);
+5
source

Source: https://habr.com/ru/post/1656302/


All Articles