我在博客文章中传递两个ID时遇到问题。第一个身份证 显示一个帖子,第二个显示帖子数量。 每个都分别很好地工作,但在整合两个,它选择一个 错误的帖子。
这是第一个获取评论的模型的代码
class News_model extends CI_Model {
function get_comment($id)
{
$this->db->select('comments.*,users.username');
$this->db->from('comments');
$this->db->join('users','users.id = comments.user_id', 'left');
$this->db->where('post_id',$id);
$this->db->order_by('date_added','asc');
$query = $this->db->get();
return $query->result_array();
}
}
这是获取帖子的模型
class News_model extends CI_Model {
function get_one_news($news_id)
{
$this->db->select('*, news.id as id');
$this->db->from('news');
$this->db->join('users' , 'users.id = news.user_id');
$this->db->where('news.id' , $news_id);
$query = $this->db->get();
return $query->first_row('array');
}
function latestnews() {
$this->db->select("
news.*,users.*,comments.*,COUNT(comments.post_id) AS num_comments");
$this->db->from('news');
$this->db->join('users' , 'users.id = news.user_id');
$this->db->join('comments' , 'comments.post_id = news.id');
$this->db->group_by('comments.post_id');
$this->db->order_by('news.date_added','desc');
$this->db->limit(4);
$query = $this->db->get();
return $query->result_array();
}
}
这是我的控制器
function view($id)
{
$data['news'] = $this->news_model->get_one_news($id);
$data["latest_news"] = $this->news_model->latestnews();
$data['comments'] = $this->m_comment->get_comment($id);
$data['content'] = 'single'; // template part
$this->load->view('includes/template',$data);
}
最后是视图文件
<div id="sidebar" class="col-md-3 fix-left">
<!---- Start Widget ---->
<div class="widget wid-vid">
<div class="heading">
<h4>Latest News</h4>
</div>
<div class="content">
<div class="tab-content">
<div id="most" class="tab-pane fade in active">
<div class="post wrap-vid">
<?php if(count($latest_news)) {
foreach($latest_news as $l_news){ ?>
<div class="zoom-container">
<div class="zoom-caption">
<a href="<?php echo base_url()?bulletins/view/<?php echo $l_news['id']?>"></a>
</div>
<img src="<?php echo base_url('assets/images/'.$l_news['image'])?>"
style="height:80px;width:100px;"/>
</div>
<div class="wrapper">
<h5 class="vid-name"><a href="<?php echo base_url('bulletins/view/'.$l_news['id'])?>"><?php echo
substr(strip_tags($l_news['title']), 0, 15).'..';?></a></h5>
<div class="info">
<h6>By <a href="#"><?php echo $l_news['username']?></a></h6>
<span><i class="fa fa-calendar"></i><?php echo date( 'F jS, Y' , strtotime($l_news['date_added']))?></span>
<span><i class="fa fa-comment-o">/i><?php echo
$l_news['num_comments'];?></span>
</div>
</div>
<?php }}?>
</div>
</div>
</div>
</div>
</div>
答案 0 :(得分:1)
请检查下面提到的解决方案。您的select cause
中有错误。如果需要来自CI中多个表的数据,并且columnName
与CI相同,则查询构建器将覆盖该列的值。在这种情况下,您需要将alias
提供给columnName
。请查看以下内容。
$this->db->select('news.id as newsId,users.id as userId,news.*,users.*,comments.*, COUNT(comments.post_id) as num_comments');
在您的视图文件中,您需要更改以下代码。
查找$l_news['id']
并替换为$l_news['newsId']
这将解决您的问题。如果它不适合你,请告诉我。