Cakephp在foreach中查找
我有一个名为Post的模型和另一个名为Comment的模型,在Comment中我有一个名为Post_id的字段。。。帖子有很多评论,评论属于帖子 我希望在纯php中列出帖子和下面的评论:Cakephp在foreach中查找,php,cakephp,cakephp-2.0,Php,Cakephp,Cakephp 2.0,我有一个名为Post的模型和另一个名为Comment的模型,在Comment中我有一个名为Post_id的字段。。。帖子有很多评论,评论属于帖子 我希望在纯php中列出帖子和下面的评论: <?php foreach ($posts as $post){ echo "<h3>" .$post['title']. "</h3>"; $sel = mysql_query("SELECT * FROM comments WHERE post_id =". $post
<?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。。很抱歉,上面的代码是从cakephp数据库中获取数据的错误方法 因为我认为你们的模型之间的关系是完美的 因此,您可以通过简单的
find()
查询
$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] => info@jamesfairhurst.co.uk
[text] => This is a sample comment.
[created] => 0000-00-00 00:00:00
)
[1] => Array
(
[id] => 2
[post_id] => 1
[name] => James
[email] => info@jamesfairhurst.co.uk
[text] => This is another sample comment.
[created] => 0000-00-00 00:00:00
)
)
)
如果我能为您提供更多帮助,请告诉我。在PostsController中,使用
find('all')
查询设置变量$posts
,以返回包含与Post
模型相关的所有Post和记录的对象,您的方法可能类似于:
PostsController:
然后在您的视图中,只需迭代$posts即可显示标题和相关注释
Posts/view.ctp:
看到和
从文件中:
如果该id未随exists()一起提供,它将调用Model::getID()以
获取要验证的当前记录id,然后执行
模型::在当前配置的数据源上查找('count'),以
确定持久存储中是否存在该记录
如果数据库中不存在任何记录,则应始终引发某种类型的异常。只有在使用可包含行为时,“包含”才会起作用,“注释”数组才会返回。bro您的asnwear很酷,但不是我想要的。。我会在同一个地方列出所有帖子,我不会通过$id。。我将列出所有帖子,并在每个帖子中显示所有评论。。我用php编写的代码解释了这一点。。会是这样的。。。帖子1
循环评论帖子1
帖子2
循环评论帖子2。。在这种情况下,只要用find('all')替换find('first')查询并删除id参数,我就编辑了我的答案来反映find('all'),非常简单的东西。。它就在文档中。
public function view() {
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('posts', $this->Post->find('all'));
}
<?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;?>