Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cakephp sum() on single field

Tags:

cakephp

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'))));
like image 204
Keith Power Avatar asked Feb 24 '26 12:02

Keith Power


2 Answers

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.

like image 92
mark Avatar answered Feb 27 '26 03:02

mark


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']
like image 40
Teej Avatar answered Feb 27 '26 04:02

Teej



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!