2013-05-09 112 views
-1

我有一个叫做Post的模型,另一个叫Comment和on Comment我有一个叫做post_id的字段... Post有很多评论和评论属于帖子。Cakephp里面找到一个foreach

我想名单的帖子和评论波纹管,在纯PHP将是类似的东西:

<?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>"; 
} 
} 
?> 

我使用的蛋糕2.x的..谢谢

回答

1

在你的PostsController,设置变量$postsfind(‘all’)查询以返回包含与Post型号相关的所有帖子和记录的对象,您的方法可能如下所示:

PostsController:

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

    $this->set('posts', $this->Post->find('all')); 
} 

然后在您的视图,只是遍历$帖子显示标题和相关评论。

帖子/ 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;?> 

参见Retrieving your dataAdditional methods and properties

从文档:

如果ID不具有存在(),它调用Model :: getID()到 获取当前记录的id验证,然后在当前配置的数据源上执行 Model :: find('count')至 确定持久存储器中是否存在该记录。

如果数据库中不存在任何记录,则应始终引发某种异常。

+0

兄弟你的asnwear冷却,但不是我想..我会列出所有帖子在同一个地方,我不会传递$ id ..我会列出所有帖子,并显示每个帖子内的所有评论..我的代码在PHP解释那更好..会是这样的东西... post 1
loop评论post1
post 2
loop评论post 2 .. etc .. – 2013-05-10 00:32:15

+0

那么在这种情况下,只需将find('first')查询替换为find 'all')并删除id参数,我只是编辑了我的答案以反映find('all'),非常简单的东西..它在文档中是正确的。 – dcd0181 2013-05-10 02:54:25

2

遗憾地说,但上面的代码在CakePHP的

来从数据库中的数据错误的方法正如我假设模型之间的关系是完美

这样你就可以从简单的得到查询像

$this->set('post', $this->Post->find('first', array(
    'conditions'=>array('Post.id'=>$id), 
    'contain'=>array('Comment') 
))); 

会给你输出鉴于像

Array 
(
    [Post] => Array 
     (
      [id] => 1 
      [title] => The title 
      [body] => This is the post body. 
      [created] => 2007-12-28 13:54:34 
      [modified] => 
     ) 
    [Comment] => Array 
     (
      [0] => Array 
       (
        [id] => 1 
        [post_id] => 1 
        [name] => James 
        [email] => [email protected] 
        [text] => This is a sample comment. 
        [created] => 0000-00-00 00:00:00 
       ) 
      [1] => Array 
       (
        [id] => 2 
        [post_id] => 1 
        [name] => James 
        [email] => [email protected] 
        [text] => This is another sample comment. 
        [created] => 0000-00-00 00:00:00 
       ) 
     ) 
) 

让我知道,如果我能帮助你更多......

+0

“包含”仅在使用可容忍行为时才起作用,无论如何将返回“Comment”数组。 – 2013-05-09 15:26:29