0

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

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

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

4

2 回答 2

5

添加first()到您的查询中,请参阅手册

$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);
于 2016-05-17T06:39:12.483 回答
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;
于 2016-05-17T07:29:31.203 回答