Query builder fetch data in cakephp 3.2

最后都变了- 提交于 2019-12-12 03:44:55

问题


I am using this below code to sum up all my wallet balance .

$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 have tried to get single individual value using below query

echo $query->total_price;

I am not getting it. What is the proper syntax ,plz suggest me. Thanx.


回答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;



回答2:


add first() to your query, see the 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);


来源:https://stackoverflow.com/questions/37268510/query-builder-fetch-data-in-cakephp-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!