Cakephp - 从数据库中随机选择并查看

发布于 2025-01-08 20:24:22 字数 313 浏览 2 评论 0原文

我需要在我的帖子查看功能中创建三个指向其他帖子的随机链接。

控制器:

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

但我不知道如何为此编写foreach。

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

世界如花海般美丽 2025-01-15 20:24:22

这将取决于您从 Post 返回的字段。我会将控制器代码稍微更改为:

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

然后在视图中,在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']));
}
?>

请务必将HTML链接中的字段更新为那些符合 Post 模型返回的内容。

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.

望笑 2025-01-15 20:24:22

在我的本地计算机上,此代码可以正常工作,但在实时服务器上,它仅生成一次随机 id,之后重复相同的 id

$max =
  $this->Article->find('first',
                       array('conditions'=>array('Article.status'=>'Active'),
                       'order' => 'rand()'));

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()'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文