【问题标题】:Query builder fetch data in cakephp 3.2查询生成器在 cakephp 3.2 中获取数据
【发布时间】:2016-05-17 06:17:21
【问题描述】:

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

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

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

【问题讨论】:

    标签: cakephp cakephp-3.x cakephp-3.2


    【解决方案1】:

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

    【讨论】:

    • 没有得到结果。
    • 添加更多信息:你得到了什么?生成什么查询?当你debug($query) 时你会得到什么?
    • Yes degug($query) 返回结果,但是 debug($query->total_price) ,这个抛出错误。我没有得到单个值。
    【解决方案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]);
    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;
    

    【讨论】:

    • 是的,foreach 正在工作,我得到了准确的结果。第二个不工作(回答或)。
    • 好的。谢谢,我得到了答案。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2019-08-12
    • 2015-08-30
    • 2015-11-20
    相关资源
    最近更新 更多