可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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');