codeigniter具有多个类别的重复条目

时间:2015-12-10 09:28:52

标签: php mysql codeigniter

我是codeigniter&的新手PHP。需要一些帮助。
我试图将我的博客文章显示在博客视图中时遇到了麻烦 表:

   blog        category      blog_category
| ------- |  | -------- |  | ------------- |
| blog_id |  |  cat_id  |  |     cat_id    |
| title   |  | cat_name |  |    blog_id    |
| content |  | cat_slug |

在我的博客控制器中:

defined('BASEPATH') OR exit('No direct script access allowed');

class Blog extends CI_Controller {

    /*
     * Blog Controller
     */

    public function __construct()
    {
        parent::__construct();
        $this->load->model('blog_model');
    }
    public function index()
    {
        $this->data = array(
            'title' => 'Blog',
            'blog' => $this->blog_model->get_all_post(),
        );

        $this->load->view('main/blog', $this->data);
    }
}

在我的博客模型中:

function get_all_post() {
    $this->db->select('*');
    $this->db->from('blog');
    $this->db->join('blog_category', 'blog_category.blog_id=blog.blog_id', 'left');
    $this->db->join('category', 'blog_category.cat_id=category.cat_id');
    $query = $this->db->get();
    $select = array();
    foreach($query->result() as $row) {
        $select[] = $row;
    }
    if (count($select) > 0)
        return $select;
    return NULL;
}

在我的博客视图中:

<?php foreach ($blog as $item): ?>
<h3 class="post-title"><a href="#"><?php echo $item->title;?></a></h3>
<p class="category"><?php echo $item->categories;?></p>
<?php endforeach;?>

当我尝试访问该视图时,它显示2 Post具有相同记录但具有不同类别。在我的博客帖子中有2个类别并逐个显示,如果在我的帖子中有3个类别,则结果显示3个帖子,其中3个类别逐个显示。 抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

加入是错误的,

$this->db->join('blog_category', 'blog_category.blog_id=blog.blog_id', 'left');
                ^// its blog_category
$this->db->join('blog_category', 'blog_category.cat_id=category.cat_id');

然后使用,

$this->db->group_by("blog.blog_id");// removes duplicates.