cakephp查询中的sum()函数

Key*_*lia 6 cakephp

我正在使用此查询,但它没有返回ctotal.请帮忙.

$total = $this->RequestedItem->find('all',
    [
        'sum(cost * quantity) AS ctotal', 
        'conditions' => [
            'RequestedItem.purchase_request_id' => $_GET['po_id']
         ]
     ]
);
Run Code Online (Sandbox Code Playgroud)

dog*_*c69 14

您不应该直接在CakePHP中使用PHP superglobals.您应该使用Model.field命名,这样就不会出现模糊的字段错误.

虚拟领域是要走的路,但这不是你的问题,你需要更多地阅读这本书.

$total = $this->RequestedItem->find('all', array(array('fields' => array('sum(Model.cost * Model.quantity)   AS ctotal'), 'conditions'=>array('RequestedItem.purchase_request_id'=>$this->params['named']['po_id'])));
Run Code Online (Sandbox Code Playgroud)

应该可以正常工作,使用virtualFields

var $virtualFields = array('total' => 'SUM(Model.cost * Model.quantity)');
$total = $this->RequestedItem->find('all', array(array('fields' => array('total'), 'conditions'=>array('RequestedItem.purchase_request_id'=>$this->params['named']['po_id'])));
Run Code Online (Sandbox Code Playgroud)

字段进入"字段"键,就像条件进入"条件"键一样.见http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find


mah*_*247 8

这也有效,对我来说很好

    $sum = $this->Modelname->find('all', array(
    'conditions' => array(
    'Modelname.fieldname' => $conditions),
    'fields' => array('sum(Modelname.fieldname) as total_sum'
            )
        )
    );
Run Code Online (Sandbox Code Playgroud)