Keith Power
Keith Power

Reputation: 14141

cakephp sum() on single field

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

Answers (3)

ISEVA
ISEVA

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

Teej
Teej

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

mark
mark

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

Related Questions