如何使用codeigniter从类别id获取类别的结果父名称

时间:2016-08-25 07:45:53

标签: sql codeigniter

请帮帮我,如何获取类别的父名称。我有这样的表。

table Category
+-------------+-----------------+-----------------+---------------+
| category_id | category_name   | category_parent | category_slug |
+-------------+-----------------+-----------------+---------------+
|           7 | Framework CSS   |               0 |               |
|           9 | Bootstrap       |               7 |               |
|          10 | Material Design |               7 |               |
+-------------+-----------------+-----------------+---------------+

table relationship
+-----------------+---------+-------------+
| relationship_id | post_id | category_id |
+-----------------+---------+-------------+
|              35 |      59 |           9 |
+-----------------+---------+-------------+

我使用codeigniter,我有一个功能来获取帖子和类别。

public function post_detail($tableName, $where = '')
{
    $post_title = $this->uri->segment(3);

    $query = $this->db->query("SELECT p.*, r.*, c.* FROM tbl_relationship AS r 
        INNER JOIN tbl_posts AS p ON r.post_id = p.post_id
        INNER JOIN tbl_category AS c ON r.category_id = c.category_id
        WHERE p.post_name = '$post_title'
    ");
    return $query->result();    
}

功能结果:(7和bootstrap)。如何得到7的父名。?

1 个答案:

答案 0 :(得分:1)

试试这个:

public function post_detail($tableName, $where = '')
{
    $post_title = $this->uri->segment(3);

    $query = $this->db->query("SELECT p.*, r.*, c.*, c1.category_name as parent_name FROM tbl_relationship AS r 
        INNER JOIN tbl_posts AS p ON r.post_id = p.post_id
        INNER JOIN tbl_category AS c ON r.category_id = c.category_id
        INNER JOIN tbl_category AS c1 ON c.category_parent = c1.category_id
        WHERE p.post_name = '$post_title'
    ");
    return $query->result();    
}