2

我在尝试使用 slug 从该表中获取结果时遇到了麻烦。

| id | parent | slug       | name       |  
-----------------------------------------
|  1 | 0      | animations | animations |
|  2 | 1      | flash      | flash      |
|  3 | 2      | looped     | looped     |
|  4 | 1      | gif        | gif images |

例如,我需要获取父类是“动画”而子类是“flash”的类别。

真正的问题是因为我需要使用 category/$parent_slug/$child_slug 搜索结果,而不是使用 ID (category/$id) 来获取|3|2|looped|looped|.

这是我到目前为止:

function get_category_childrens($category_parent=null){
    $this->db->select('*');
    if(!is_null($category_parent)){
        $this->db->where('categories.slug', $category_parent);
        $this->db->join('categories as l1', 'l1.parent = categories.id', 'left');
    }
    else{
        $this->db->where('categories.parent', '0');
    }
    $query = $this->db->get('categories');
    return $query->result_array();
} 

生成的sql:

SELECT *
FROM (`categories`)
LEFT JOIN `categories` as l1 ON `l1`.`parent` = `categories`.`id`
WHERE `categories`.`slug` = 'animations'  

如果您不了解 CI,没问题,如果您有疑问或想法,请发表评论。

4

2 回答 2

3
SELECT *
FROM (`categories` as l1)
LEFT JOIN `categories` as l2 ON `l2`.`parent` = `l1`.`id`
LEFT JOIN `categories` as l3 ON `l3`.`parent` = `l2`.`id`
WHERE `l1`.`slug` = 'animations'
AND `l2`.`slug` = 'flash'
于 2011-02-12T18:05:18.827 回答
2
SELECT categories.*
FROM categories
LEFT JOIN categories AS parent ON categories.parent = parent.id
LEFT JOIN categories AS child ON categories.id = child.parent
WHERE (parent.name='animations') and (child.name = 'flash')

是我认为你所追求的。

于 2011-02-12T17:34:23.623 回答