【问题标题】:mySQL hierarchical query on codeigniter在 codeigniter 上的 mySQL 分层查询
【发布时间】:2011-06-26 03:42:51
【问题描述】:

我在尝试使用 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 没问题,如果你有疑问或想法请评论。

【问题讨论】:

    标签: mysql codeigniter hierarchical


    【解决方案1】:
    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'
    

    【讨论】:

    • l4 l5 l6 l7 l8 l9 l10..ln。不错的答案
    【解决方案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')
    

    是我认为你所追求的。

    【讨论】:

    • 这不行,你在第二次加入 xP 时弄乱了关系
    • 怎么样?你说“父母是动画,孩子是Flash”。
    猜你喜欢
    • 2020-12-27
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-03-02
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多