Paginate associated model's data in CakePHP

This is a pretty simple tip, but I’ve noticed some beginners are having a problem with this scenario.

We are in the Users Controller and need to paginate all Comments for a given User (i.e. User.id = 5), well and probably display the User info while we are at it…
For this example we keep in mind that User hasMany Comment and Comment belongsTo User.

First, we prepare our controller to handle Comment pagination:

class UsersController extends AppController
{
    var $name = 'Users';

    var $paginate = array('Comment'=>array('limit'=>5));
}

Yep, even though we are in the Users Controller, we will be paginating the Comment model. (Obviously you can add other options, but we’ll just add a simple ‘limit’ for this example).

So what’s left to do?
Tell our paginate() method that we’ll be paginating the Comment model and pass appropriate User.id in the array of conditions:

[source language=”php”]
function index() {
$this->set(‘comments’, $this->paginate($this->User->Comment, array(‘User.id’=>5)));
}
[/source]

Remember, that because Comment belongsTo User, cake will build a JOIN and pass the correct condition to retrieve all of the relevant comments for this User.

… and for a little extra bonus let’s throw in a simple view:

<?php echo $paginator->numbers(); ?>

<?php foreach($comments as $comment): ?>

<div>
    <?php echo $comment['Comment']['comment']; ?>
</div>

<?php endforeach; ?>
%d bloggers like this: