简体   繁体   中英

Get all categories of posts

im using Codeigniter. I wanted to show all posts with their respective categories. i have made a code but it is only showing one category of the post. why my code is not getting all the categories of the post? any solution or improvement will be good. here are my codes:

$this->db->select("posts.*, categories.*");
$this->db->from( 'posts' );

//get cats
$this->db->join('post_cat', 'posts.post_id = post_cat.post_id', 'LEFT');
$this->db->join('categories', 'post_cat.cat_id = post_cat.cat_id', 'LEFT');

//get published blogs
$this->db->where('post_type', 'blog');
$this->db->where('post_status', 'published');

$this->db->group_by("posts.post_id");
$this->db->order_by("post_id", "desc");

$query = $this->db->get();

return $query->result_array();

I guess you did a typo here.

Try below code:

$this->db->select("posts.*, categories.*");
$this->db->from( 'posts' );

//get cats
$this->db->join('post_cat', 'posts.post_id = post_cat.post_id', 'LEFT');
$this->db->join('categories', 'post_cat.cat_id = categories.id', 'LEFT');
// you did typo in above statement here ==> post_cat.cat_id = post_cat.cat_id

//get published blogs
$this->db->where('post_type', 'blog');
$this->db->where('post_status', 'published');

$this->db->group_by("posts.post_id");
$this->db->order_by("post_id", "desc");

$query = $this->db->get();

return $query->result_array();

i found the solution and here it is:

//select posts,cats,tags
$this->db->select("posts.*, GROUP_CONCAT(DISTINCT categories.cat_slug,'-',categories.cat_name) as cat",FALSE);
$this->db->from('posts');

//join cats
$this->db->join('post_cat', 'post_cat.post_id = posts.post_id', 'LEFT');
$this->db->join('categories', 'categories.cat_id = post_cat.cat_id', 'LEFT');

//get published blog
$this->db->where('post_type', 'blog');
$this->db->where('post_status', 'published');

$this->db->group_by("posts.post_id");
$this->db->order_by("post_id", "desc");

$query = $this->db->get();

return $query->result_array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM