How I can create trees via DB
Moderator: General Moderators
How I can create trees via DB
I wanna create shop. It will have some categories (for example: Electronics -> Tablets -> iPad or Antique->Coins or Electronics -> PCs). As you see, I have dunamic quantity of "levels". And here is a question: how I can store the trees and display it in a browser? All categories must be clickable. I had an idea to store the categories in other table (as text) and compare it with numeric id, but I think that is bad idea. Is there a better way?
Re: How I can create trees via DB
It might not be, depending on what you were thinking (hard to tell with just that description).bagi wrote:I had an idea to store the categories in other table (as text) and compare it with numeric id, but I think that is bad idea.
Two tables.
First table is just for a list of categories. It has an ID for each category, the name of course, and an optional ID for the parent category's ID (if the category has a parent category). Maybe other fields if you want.
Code: Select all
id | name | parent
---+-------------+-------
1 | Electronics | NULL
2 | Tablets | 1
3 | iPad | 2
4 | Antique | NULL
5 | Coins | 4
6 | PCs | 1Code: Select all
product | category
--------+---------
123 | 3 (if product ID=123 is an iPad)
234 | 2 (if product ID=234 is a non-iPad tablet)
345 | 2 (product ID=345 is that one Windows 8 laptop that's also a tablet)
345 | 6Re: How I can create trees via DB
While this example is cakephp specific, they do a good job at showing how to manage and use trees in a database using a parent then left and right. This follows the idea of Modified Preorder Tree Traversal (MPTT) logic.
Re: How I can create trees via DB
Oh, yeah! That's I need. But how I can create "union" with two variables? For example, in c++ i can create struct with two variables and via push_back method (in object of vector class) add it to tail. After I have assess to all data by id: 0..size()-1 and I have ids and names don't touched. How I can realize it in php? I wanna get id,name (of category and all parents) and add it into array. After I would like to have access do like this: categories[0].name categories[0].id (this is general parent), categories[1].name categories[1].id (this is child of general parent) and ect