Reputation: 714
I have an issue getting the subcategories from the same table, the subcategories have a parentid that represent the main category.
Where i'm wrong ?
My structure is the next.
Controller:
$cats = $this->categories_model->getCategories();
foreach($cats as $ct){
$cat_id = $ct->id;
}
$data['categories'] = $this->categories_model->getCategories();
$data['subcategories'] = $this->categories_model->getSubcategories($cat_id);
Model:
public function getCategories() {
$query = $this->db->get_where('categories', array('visible' => 1, 'parentid' => 0));
return $query->result();
}
function getSubcategories($cat_id) {
$this->db->select('*');
$this->db->from('categories');
$this->db->where(array('parentid' => $cat_id, 'visible' => 1));
$query = $this->db->get();
return $query->result();
}
View:
<h4>Categories</h4>
<div class="list-group categories">
<?php foreach($categories as $category): ?>
<a href="<?php echo site_url() . '/products/catalog_list/' . $category->id ; ?>" class="list-group-item"><?php echo $category->name ; ?><span class="glyphicon glyphicon-chevron-right"></span></a>
<?php foreach($subcategories as $subcategory): ?>
<div class="list-subgroups">
<a href="<?php echo $subcategory->id; ?>" class="list-subgroup-item"><?php echo $subcategory->name; ?></a>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
</div>
Table data:
id parentid name description metatags visible
1 0 Boots Boots boots 1
2 1 Man boots man boots NULL 1
3 1 Women boots women boots NULL 1
5 0 Jackets Jackets NULL 1
6 5 Women jackets Women jackets NULL 1
Upvotes: 1
Views: 6409
Reputation: 10041
I think you are going wrong in your controller. You currently have
$cats = $this->categories_model->getCategories();
foreach($cats as $ct){
$cat_id = $ct->id;
}
$data['categories'] = $this->categories_model->getCategories();
$data['subcategories'] = $this->categories_model->getSubcategories($cat_id);
You are assigning $cat_id
and doing nothing with it inside your foreach
loop. You are only using the last category id to select the subcategories.
You are going to want to rearrange your code so that you can get all of the sub categories for your current categories.
This may involve a little more than just putting your subcategory selection code into the loop, because you would then be overwriting your variable each time, having a similar effect.
Upvotes: 1