cakephp查询中的sum()函数

时间:2011-02-11 15:55:52

标签: cakephp

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

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

4 个答案:

答案 0 :(得分: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'])));

应该可以正常工作,虚拟目标就是

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

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

答案 1 :(得分:8)

这也有效,对我来说很好

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

答案 2 :(得分:3)

在进行查找之前暂时设置virtualFields。

$this->MaterialScan->virtualFields = array(
    'total_qty' => 'COUNT(MaterialScan.id)',
    'total_lbs' => 'SUM(MaterialScan.weight)'
);
$materialScans = $this->MaterialScan->find('all',array(
    'conditions' => array(
        'MaterialScan.id' => $scans
    ),
    'group' => array('MaterialScan.part_number')
));

这避免了返回数组中的[0]元素。

答案 3 :(得分:2)

您可以使用virtualFields:

var $virtualFields = array(
    'the_sum' => 'SUM(Model.cost * Model.quantity)'
);