查询生成器在 cakephp 3.2 中获取数据

Query builder fetch data in cakephp 3.2

我正在使用下面的代码来总结我所有的钱包余额。

$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;

输出 pj($query);

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

在这里,我尝试使用以下查询获取单个值

echo $query->total_price;

我不明白。 什么是正确的语法,请建议我。 谢谢

first() 添加到您的查询中,请参阅 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);
$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;