mySQL hierarchical query on codeigniter

2.3k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER
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'
2
On
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')

is what I think you're after.