Custom group by pagination and a calculated field
This is a basic example of how to use the CakePHP paginator helper with the group by condition, it took a little mucking around but this is how I got it working.
In this example we have a Comment controller which I want to paginate a custom query displaying an IP address and a calculated count field of the number of spam comments from these particular IP addresses.
In the Controller
The CommentController code looks like the following :-
Show Plain Text- function admin_index($filter=null) {
- $this->Comment->recursive = 0;
- if ($filter == 'count') {
- 'Comment.id', 'Comment.ip', 'Count(Comment.ip) as Count'
- ),
- 'Comment.status = 0'
- ),
- 'Comment.ip'
- ),
- 'Count' => 'desc'
- )
- );
- $data = $this->paginate('Comment', $conditions);
- } else {
- if ($filter == 'spam') {
- } else {
- }
- 'Comment.id' => 'desc'
- )
- );
- }
- $data = $this->paginate('Comment', $conditions);
- }
I did have the order by condition set in the var paginator initialization array() but for some reason this was always being ignored, I didn't investigate why but found that setting the condition through $this->paginate['Comment'] worked a treat.
In the Model
The next key part with the group by condition is to override the models paginateCount() method in the Comment model as follows :-
Show Plain Text- $this->recursive = $recursive;
- $count = $this->getAffectedRows();
- }
- return $count;
- }
For my particular group by pagination I actually wanted the $count to represent the number of rows returned by the count query.
In the view
Also if your passing arguments in your url you need to tell the paginator to pass them along as well, so in your view you need this line somewhere :-
Show Plain TextThe Calculated field
The other thing to note is that the calculated field is added by CakePHP to the zero index of the array. So for this example the calculated Count field will be found under ['0']['Count'], if you want to move this field to your main index you will need to write a afterFind() function.
Anyway thats how I got it to work, hope its of help to someone.
Many thanks for posting this, your custom paginateCount function has just saved me hours of frustration.