Reputation: 89
This is the scenario: I have a Posts
Model and each post has a Meta
attached through $hasMany
. The Meta model contains a view counter, a download counter, etc.
This is done this way to avoid updating the Post every time a user visits a post, and because I'll have another index where the most recently modified posts will reside, so changing a Post on every visit defeats the purpose of the "recently modified" index so the views
and downloads
are saved in Meta.
How can I order the Posts index view with pagination using the data from the Meta model like downloads so the Posts are sorted by downloads?
I hope that's clear enough, if you need more data please leave a comment below.
Upvotes: 1
Views: 124
Reputation: 2974
First, you need to declare the paginate settings, like this
$this -> paginate = array(
'limit' => 3, // your desired limitation
'contain' => array('Meta'),
'fields' => array(
'Post.title',
'Post.date_published',
...,
'Meta.downloads',
'Meta.views'
),
'order' => 'Meta.downloads {ASC|DESC}'
);
Then you can paginate like this:
$this -> set('posts', $this -> paginate('Post'));
assuming your Models are called Post and Meta.
EDIT In order for this to work (the contain key in the paginate array), you need to add the Containable behavior to the Meta model:
public $actsAs = array('Containable');
Upvotes: 1