我是PHP和Codeigniter(v2.0)框架的新手。希望你能帮助我找到我的方式通过我的第一个web应用程序。详情如下,并提前感谢!
目标/问题总结:我想在我的视图中显示所有的blog_Comments,附加到每个特定的blog_Post。
Details: My blog_Posts表包含所有原始博客文章[id(int),标题,条目,作者(all varchar)和日期(timestamp)]。我的blog_Comments表[id(int), entry_id(int), author, comment(varchar)]包含所有注释;它们通过*entry_id*属性与原始的blog_Post相关联。
控制器:
$query1 = $this->blog_model->get_posts();
$query2 = $this->blog_model->get_comments();
$data = array();
$data['posts'] = $query1;
$data['comments'] = $query2;
模型:
function get_posts() {
$query = this->db->get('blog_Posts');
return $query->result;
}
function get_comments() {
$query = this->db->get('blog_Comments');
return $query->result;}
视图:
<?php if(isset($posts)) : foreach($posts as $posts=>$row) : ?>
<?php $row->title; ?>
<?php $row->author; ?>
<?php $row->entry; ?>
<?php foreach($comments as $comments=>$com) : ?>
<?php if($com->entry_id == $row->id) : ?>
<p>author: <?php echo $com->author; ?></p>
<p>comment: <?php echo $com->comment; ?></p>
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php else : ?> <p>no blog_Posts found</p>
<?php endif; ?>
编辑/更新:
我试图将注释粘贴到上面的视图代码块中,我还列出了它给我的两个问题。现在我有两篇示例原创博客文章,以及与之相关的评论。
问题:
- 第一个博客条目(第一次通过循环),它显示所有评论,包括与其他entry_id s相关的评论。
- 第二个博客条目(第二次通过循环),它抛出以下错误:"为foreach()提供的无效参数",并指向我的视图中包含foreach用于$comments的行。
简而言之,我试图只查看那些具有与原始帖子"id"匹配的entry_id的评论。
再次感谢您的帮助和时间。
aj
既然你不需要一次显示所有的评论,你可以像下面这样修改你的get_comments函数来返回每个帖子的评论,当然,按照你的方式显示它们,按创建日期,最后条目等排序:
所以对于模型部分:
function get_comments($post_id){
$query = $this->db->query("select * from `blog_Comments` where `entry_id` = $post_id ORDER BY `created_on` DESC");
if($query->num_rows() != 0){
return $query->result();
}else{
return false;
}
}
在视图文件中:
foreach($posts as $row){
echo 'Title: ' . $row->title .
'Author: ' . $row->author .
'Entry:' . $row->entry;
$comments = $this->blog_model->get_comments($row->id);
if(!$comments){
echo 'No comments';
}else{
foreach($comments as $com){
echo $com->comments . '<br/>' . $com->user . '<br/>' . etc etc
}
}
}
我懒得测试,但我认为你正在尝试使用$row,但你在foreach的定义之外。在这里引入$row
<?php if(isset($posts)) : foreach($posts as $posts=>$row) : ?>
然后关闭foreach——所以$row在这里不再可用:
<?php if($com->entry_id == $row->id); ?>
是的。但是实际上你应该在控制器和模型中做尽可能多的逻辑和检查。验证你的数据对象——比如Posts——然后控制器决定正确的视图。如果没有任何帖子要显示,你不会有混乱的'如果没有帖子'条件句在你的视图中。你只需要调用no posts视图文件。