I have basically the following table,
Categories
id name categories_id_categories
1 Clothes null
2 Shirts 1
3 Pants 1
4 Electronics null
5 Tv 4
The table stores categories and sub-categories, if the categories_id_categories is null theyre main categories else theyre sub-categories of the category with that id. I want to show this on a page so I created this functions on my Categories model:
public function getAllCategories()
{
$select = $this->select()
->where('categories_id_categories IS NULL');
return $this->fetchAll($select);
}
public function getAllSubCategories()
{
$select = $this->select()
->where('categories_id_categories IS NOT NULL');
return $this->fetchAll($select);
}
And on my controller:
$categories = new Model_DbTable_Categories();
$categoryList = $categories->getAllCategories();
$categoriesAll = array();
foreach ($categoryList->toArray() as $category) {
$subCategories = $categories->getSubCategoriesByCategory($category['id']);
$category['sub_categories'] = $subCategories->toArray();
$categoriesAll[] = $category;
}
$this->view->categoryList = $categoriesAll;
So categoryList is an array with all the categories and the key sub_categories is another array with all sub-categories. This works but I was wondering if there was a way to do it using objects instead of an array, and maybe using just one query instead of 2?
If I select all from the table I'd get categories and sub-categories but then I'd have to move some logic into the view to select the sub-categories I believe.
Thanks in advance!
Just put $id to getAllSubcategories and create getSubCategories in your model like this:
public function geSubCategories($id = null) { $select = $this->select(); if ( $id == null ) { $select->where('categories_id_categories IS NOT NULL'); } else { $select->where('id = ?', $id); } return $this->fetchAll($select); }