我试图使用slugs从这张表中获得结果很麻烦。
| id | parent | slug | name |
-----------------------------------------
| 1 | 0 | animations | animations |
| 2 | 1 | flash | flash |
| 3 | 2 | looped | looped |
| 4 | 1 | gif | gif images |
例如,我需要获取父级为“动画”且子级为“闪光”的类别。
真正的问题是因为我需要使用类别/ $ parent_slug / $ child_slug搜索结果,而不是使用ID(类别/ $ 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,没问题,如果您有疑问或想法,请发表评论。
答案 0 :(得分: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'
答案 1 :(得分: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')
是我认为你想要的。