cakephp sum() on single field

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I have searched high and low on how to just get a total of a field called points. I just need one total figure but the best I can get is a list of records from the Points table with the associated records from the Members.

    $totalPoints = $this->Member->Point->find('all', array(                array('fields' => array('sum(Point.points)   AS Point.ctotal')))); 

回答1:

Why not using virtualFields as documented and suggested by the docs? http://book.cakephp.org/2.0/en/models/virtual-fields.html

$this->Member->Point->virtualFields['total'] = 'SUM(Point.points)'; $totalPoints = $this->Member->Point->find('all', array('fields' => array('total'))); 

This is way cleaner.

Also note the double array you got there in your $options array (...find('all', array(array(...). And how I used only a single/flat array. This is the reason why your SUM() call as fields does not work.



回答2:

mark's answer above is right. I just want to add that you can do this:

$totalPoints = $this->Member->Point->find('first', array(                array('fields' => array('sum(Point.points) AS Point__ctotal')))); 

$totalPoints will be have this:

$totalPoints['Point']['ctotal'] 


回答3:

Another clean way without outputting an array

$this->Member->Point->virtualFields = array('total' => 'SUM(Point.points)'); $total = $this->Member->Point->field('total'); 


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