Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp - random select from the database and View

I need create three random links to other posts, in my post view function.

Controller:

$random = $this->Post->find('all', array( 
             'order' => 'rand()',
             'limit' => 3,
             'conditions' => array('Post.status' => 'ok') 
             )); 

But i do not know, how to write a foreach for this.

Thanks

like image 587
user1183721 Avatar asked Feb 25 '12 20:02

user1183721


2 Answers

It will depend on the fields you get back from Post. I would change the controller code just slightly to this:

$this->set('random_posts', $this->Post->find('all', array( 
   'conditions' => array('Post.status' => 'ok'), 
   'order' => 'rand()',
   'limit' => 3,
)));

Then in the view you cycle through them in the foreach:

<?php 
foreach ($random_posts as $random_post) {
    echo $this->Html->link($random_post['Post']['name'], array('controller' => 'posts', 'action' => 'view', $random_post['Post']['id']));
}
?>

Be sure to update the fields in the HTML link to those that conform to what ever comes back from the Post model.

like image 100
Chuck Burgess Avatar answered Nov 09 '22 12:11

Chuck Burgess


On my local machine this code is working but on live server it generates random id just once, after that repeats the same id

$max =
  $this->Article->find('first',
                       array('conditions'=>array('Article.status'=>'Active'),
                       'order' => 'rand()'));
like image 27
Anand Avatar answered Nov 09 '22 12:11

Anand