Cakephp pagination with random order?
-
27-10-2019 - |
문제
Ok, I have looked and looked but cannot seem to find anything on this anywhere. I have a display of results that are paginated beautifully, but they currently display in ascending order. I'd like for them to display in random order. Here is my current controller code:
public function condos() {
$this->paginate['Unit']=array(
'limit'=>9,
'contain'=>array(
'User'=>array(
'id', 'user_name', 'area_code', 'exchange', 'sln', 'email'),
'Complex'=>array('id','complex_name', 'realname', 'photo1','photo2','photo3','photo4','photo5', 'complex_website')
),
'conditions'=>array(
'Unit.type'=>array('condo', 'rentalco'),
'Unit.active'=>1)
);
$data = $this->paginate('Unit');
$this->set('allcondos', $data);
}
해결책
For anyone else finding this - the actual answer is to generate a seed (a float between 0 and 1), and save it to the session before the RAND()
sort is necessary (in the controller's beforeFilter()
). Then:
$this->paginate['order'] = sprintf('RAND(%f), $this->Session->read('seed'));
This preserves the RAND()
seed between calls to the paginator, and preserves the overall order of the results between requests.
다른 팁
This seems to work pretty well on CakePHP 2 for me:
$this->paginate = array(
'order' => 'RAND()'
);
This is using the MySQL RAND()
function, which Cake just passes on to the database.
EDIT: Now that I think about it, this is not a good idea, because the order is not maintained between pages. I can't think of a good way off the top of my head to randomize the order and maintain continuity between pages. Maybe if you were to shuffle the items on the page with JavaScript?