gpt4 book ai didi

codeigniter 上的 mySQL 分层查询

转载 作者:行者123 更新时间:2023-11-29 01:33:16 25 4
gpt4 key购买 nike

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

| 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 也没关系,如果您有任何疑问或想法,请发表评论。

最佳答案

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'

关于codeigniter 上的 mySQL 分层查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4979483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com