Codeigniter 上的 mySQL 分层查询
我在尝试使用 slugs 从该表中获取结果时遇到了麻烦。
| id | parent | slug | name |
-----------------------------------------
| 1 | 0 | animations | animations |
| 2 | 1 | flash | flash |
| 3 | 2 | looped | looped |
| 4 | 1 | gif | gif images |
例如,我需要获取父级为“动画”、子级为“闪存”的类别。
真正的问题是因为我需要使用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,没问题,如果您有查询或对此有想法,请发表评论。
I'm havin troubles trying to get the results from this table using slugs.
| id | parent | slug | name |
-----------------------------------------
| 1 | 0 | animations | animations |
| 2 | 1 | flash | flash |
| 3 | 2 | looped | looped |
| 4 | 1 | gif | gif images |
For example i need to get the categories where the parent is 'animations' and the child is 'flash'.
The real issue is because i need to search for results using category/$parent_slug/$child_slug instead use ID's (category/$id) to get |3|2|looped|looped|
.
This what i've so far:
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();
}
The sql generated:
SELECT *
FROM (`categories`)
LEFT JOIN `categories` as l1 ON `l1`.`parent` = `categories`.`id`
WHERE `categories`.`slug` = 'animations'
No problem if you dont know CI, if you've the query or an idea of it please comment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想这就是你所追求的。
is what I think you're after.