CakePHP 2.0 paginate on related model

Just a quick note on this one as it took a while to discover how to it.

Say you have a relationship between two tables and you want to be able to use the built in pagination helper to generate sort links on the content in the related table.
One way of doing this is to add virtual fields to bring the related column(s) into the Model.

In your controller:

$this->Post->virtualFields['user_name'] = 'User.name';

then in your view you can generate a sort link for this field with:

echo $this->Paginator->sort('user_name');

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.