Reputation: 14141
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'))));
Upvotes: 2
Views: 11933
Reputation: 1
Another clean way without outputting an array
$this->Member->Point->virtualFields = array('total' => 'SUM(Point.points)');
$total = $this->Member->Point->field('total');
Upvotes: 0
Reputation: 12873
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']
Upvotes: 3
Reputation: 21743
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.
Upvotes: 13