I have a table with a list of categories of different levels. I'm using the columns, category_id , category_title , category_level and category_parent_id
The following code is a part of my search script. For a given category in the search, I wish to obtain results not only belonging to the chosen category but also all child categories to this category (and the children of those etc). I've tackled it by looping through the children of the category and then the children of the children.
Is it possible to simplify this down to do one query? I want to get a string of all child categories separated by a comma so I can use it in a WHERE IN
condition.
$categories = $this->input->get('category_id');
$subquery = $this->db->where('parent_id',$categories)->get('categories');
$subcats = $subquery->result();
foreach($subcats as $cat) {
$categories .= ','.$cat->category_id;
$subsubquery = $this->db->where('parent_id',$cat->category_id)->get('categories');
foreach($subsubquery->result() as $cat) {
$categories .= ','.$cat->category_id;
}
}
Output should be something like 2, 15, 45, 15, 41, 32
I am using active record queries btw (in CodeIgniter), incase the syntax confuses you. I will have at max about 50 categories ever stored in the table and max 3 levels.