我使用以下代码来总结我的所有钱包余额。
$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;
我没有得到它。 什么是正确的语法,plz建议我。 感谢名单。
答案 0 :(得分:5)
在查询中添加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);
答案 1 :(得分:1)
$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;