How to use aggregation SQL functions with CakePHP

Have you ever wondering how to find MAX, MIN or AVG of a database table column in CakePHP way? Well I haven’t since yesterday. The solution is quite simple and obvious.

Lets say you want to show the average views per post (in the example we have the views field in every post).
The SQL should be something like this:

SELECT AVG(views) FROM posts

Instead of using query() function you can use the CakePHP way:

$this->Post->find('first', array('fields'=>array('AVG(views) as avg_views')));

Hope this will help someone.

4 thoughts on “How to use aggregation SQL functions with CakePHP

Leave a Reply

Your email address will not be published. Required fields are marked *