doupa8922 2013-05-09 03:10 采纳率: 100%
浏览 21
已采纳

Cakephp找到了一个foreach

i have a model called Post and another one called Comment and on Comment i have a field called post_id... Post has many comments and Comment belongs to post.

I want list posts and the comments bellow, in pure php will be something like that:

<?php
foreach ($posts as $post){

 echo "<h3>" .$post['title']. "</h3>";

 $sel = mysql_query("SELECT * FROM comments WHERE post_id =". $post['id']);
 $comments = mysql_fetcha_assoc($sel);

 foreach ($comments as $comment){
  echo "<p>" .$comment['comment']. "<p>";
 }
}
?>

I am using cake 2.x .. thanks

  • 写回答

2条回答 默认 最新

  • doutu2017 2013-05-09 04:23
    关注

    In your PostsController, set a variable $posts with find(‘all’) query to return an object containing all posts and records relating to the Post model, your method may look something like:

    PostsController:

    public function view() {
        if (!$this->Post->exists()) {
            throw new NotFoundException(__('Invalid post'));
        }
    
        $this->set('posts', $this->Post->find('all'));
    }
    

    Then in your view, just iterate over $posts to display the title and related comments.

    Posts/view.ctp:

    <?php foreach ($posts as $post): ?>
        <h3><?php echo $post['Post']['title']; ?></h3>
        <?php foreach ($post['Comment'] as $comment):?>
            <p><?php echo $comment['comment'];?></p>
        <?php endforeach;?>
    <?php endforeach;?>
    

    See Retrieving your data and Additional methods and properties

    From the documentation:

    If the id is not provided with exists(), it calls Model::getID() to obtain the current record id to verify, and then performs a Model::find('count') on the currently configured datasource to ascertain the existence of the record in persistent storage.

    You should always have some sort of exception thrown if no records exist in the database.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办