Unlimited Sub Categories php and mysql li list open cart categories
Question
I have the following tables category
and category_description
in php mysql. my question is how with the information below do i go about creating an unlimited amount of subcategories in a ul
li
structure. I have looked at various examples on here but no no avail many thanks for your time in reading this question. i look forward to your response
Column Type Null Default
category_id int(11) No
image varchar(255) Yes NULL
parent_id int(11) No 0
top tinyint(1) No
column int(3) No
sort_order int(3) No 0
status tinyint(1) No
date_added datetime No 0000-00-00 00:00:00
date_modified datetime No 0000-00-00 00:00:00
And the descriptions are stored in this table
Column Type Null
category_id int(11) No
language_id int(11) No
name varchar(255) No
description text No
meta_description varchar(255) No
meta_keyword varchar(255) No
Solution
opencart has the
$this->model_catalog_category->getCategory()
method, and you pass the category id as a parameter, such as
$category = this->model_catalog_category->getCategory(5);
That also handles the appropriate description join too so you don't need to access them directly. As @Till Helge Helwig has already pointed out, you need to use a recursive function if you want to build a tree of these with all the subcategories. A good place to see an example of this is in the actual category module code. Scroll to the bottom of the file catalog/controller/module/category.php
and you will see a recursive function that builds the html for it
OTHER TIPS
You already have a column parent_id
. Use that to represent the relationships between categories. If a category is at the root level, you set that column to NULL
.
Another approach would be a third table that maps categories to sub-categories. This would allow you to walk from the top down as well as from the bottom up. Depends on your application which approach you use.
In order to handle this hierarchy, you need to write some recursive functions and find a proper representation in PHP that can properly handle the category hierarchy.
A simple recursive function to print some sort of breadcrumbs would look like this (I assume in this example that you have some kind of ORM in place):
function findWayToTop($category, $breadcrumbs = array()) {
$breadcrumbs[] = $this;
$parent = $category->getParent();
if ($parent != null) {
return findWayToTop($parent, $breadcrumbs);
} else {
return $breadcrumbs;
}
}
If you don't use ORM, the easiest way is to fetch all categories from the database and store them in an array where the ID is the key. Then you can replace array calls in the code above and it works as well.