use*_*721 9 random select cakephp view
我需要在我的帖子视图功能中创建三个随机链接到其他帖子.
控制器:
$random = $this->Post->find('all', array(
'order' => 'rand()',
'limit' => 3,
'conditions' => array('Post.status' => 'ok')
));
Run Code Online (Sandbox Code Playgroud)
但我不知道,如何为此写一个foreach.
谢谢
Chu*_*ess 19
这取决于你从Post回来的字段.我会稍微改变一下控制器代码:
$this->set('random_posts', $this->Post->find('all', array(
'conditions' => array('Post.status' => 'ok'),
'order' => 'rand()',
'limit' => 3,
)));
Run Code Online (Sandbox Code Playgroud)
然后在视图中,您将在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']));
}
?>
Run Code Online (Sandbox Code Playgroud)
请务必将HTML链接中的字段更新为符合Post模型中返回的字段.