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
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.
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()'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With