CAPPHP random page?

Ok, I looked and looked, but it seems I didn’t find anything. I have a display of results that are nicely paginated, but currently they are displayed in ascending order. I would like them to be displayed randomly. 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); } 
+4
source share
2 answers

For anyone who finds this, the actual answer is to create a seed (float from 0 to 1) and store it in the session until RAND() sorted (in the beforeFilter() controller). Then:

$this->paginate['order'] = sprintf('RAND(%f), $this->Session->read('seed'));

This saves the RAND() seed between calls in the paginator and preserves the general order of the results between requests.

+6
source

This seems to work like CakePHP 2 for me:

 $this->paginate = array( 'order' => 'RAND()' ); 

This uses the MySQL RAND() function, which Cake simply passes to the database.

EDIT: Now that I think about it, this is not a good idea, because the order is not supported between pages. I can't think of a good way from the head to randomize the order and maintain continuity between pages. Maybe if you want to shuffle elements on the page using JavaScript?

0
source

Source: https://habr.com/ru/post/1390532/


All Articles