[英]Display posts according to category ID from pivot table in CodeIgniter
我目前有三个这样的表:
ci_posts: ID,标题,子词,内容。
ci_terms: term_id,标题,子词。
ci_relationship: id,post_id,term_id
我正在尝试根据特定的单击类别检索所有帖子。
这是我在模型中使用的方法,但无法按需运行:
public function get_posts_category($id){
$this->db->select('*');
$this->db->from($this->table);
$this->db->join('ci_relationship', 'ci_relationship.post_id = ci_posts.id', 'INNER');
//$this->db->join('ci_users', 'ci_users.id = ci_relationship.id', 'INNER');
//$this->db->join('ci_terms', 'ci_relationship.term_id = ci_terms.term_id', 'INNER');
$this->db->order_by('post_id', 'DESC');
$this->db->group_by('post_id');
//$this->db->where('type', 'category');
$this->db->where('term_id', $id);
$query = $this->db->get();
if($query->num_rows() >= 1){
return $query->result();
} else {
return false;
}
}
就像$ this-> db-> where('term_id',$ id)上方的代码段一样,应该可以显示与单击类别匹配的所有帖子,这些帖子存储在ci_relationship表中并在ci_terms表中创建,但是即使在ci_relationship表中有多个相互关联的ci_post和ci_terms,当前输出也不显示任何内容。
有人可以向我解释我的错误在哪里吗?
更新这是我如何访问它们:
<?php if($categories) : ?>
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Categories</h1>
</div>
<div class="panel-body">
<?php foreach($categories as $cats) : ?>
<a href="<?= base_url('posts/category/'.get_category_slug($cats->term_id)) ?>"><span class="label label-orange"><?= get_category($cats->term_id); ?></span></a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
这是我的Post控制器中的我的类别方法:
public function category($id){
$data['posts'] = $this->Post_model->get_posts_category($id);
$category = $this->Terms_model->get($id);
// Get Categories
$data['categories'] = $this->Post_model->get_categories();
// Meta
// $data['title'] = $this->settings->title.' | '. ucfirst($category->title);
// Load template
$this->template->load('public', 'default', 'posts/category', $data);
}
当标签存在于下面的ci_relationship表中时,这是控制器中用于获取标签的方法:
// Get categories
public function get_categories(){
$this->db->select('*');
$this->db->from('ci_relationship');
$this->db->group_by('term_id');
$this->db->where('type', 'category');
$query = $this->db->get();
if($query->num_rows() >= 1){
return $query->result();
} else {
return false;
}
}
但是上面的代码仅用于显示,根据单击的类别显示帖子的实际功能仍然是get_posts_category方法。
提前致谢
希望这个能对您有所帮助 :
您的get_posts_category
应该是这样的:
public function get_posts_category($id)
{
$this->db->select('*, count(ci_posts.id)');
$this->db->from('ci_posts');
$this->db->join('ci_relationship', 'ci_relationship.post_id = ci_posts.id');
//$this->db->join('ci_users', 'ci_users.id = ci_relationship.id', 'INNER');
//$this->db->join('ci_terms', 'ci_relationship.term_id = ci_terms.term_id', 'INNER');
$this->db->order_by('ci_posts.id', 'DESC');
$this->db->group_by('ci_posts.id');
//$this->db->where('type', 'category');
$this->db->where('ci_relationship.term_id', $id);
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query->result();
}
else
{
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.