View Single Post
Old 08-23-2002, 05:38 AM   #3 (permalink)
sdeming
Code Monkey
 
Join Date: Jul 2002
Location: Michigan
Posts: 85
sdeming is on a distinguished road
Well, you are brushing on heirarchical data storage, something that often baffles people because it is so bloody difficult to envision. We have troubles with the concept of infinity.

Basically, your best bet is to have a different table for tracking the heirarchies, keeping your data separate like this:
Quote:
categories:
cat_id
description
primary key on cat_id

heirarchy:
cat_id
parent_id
primary key on cat_id, parent_id
foreign key on cat_id to categories.cat_id
foreign key on parent_id to categories.cat_id
You can generate your categories however you wish. Just keep plugging em in, until they are put in the heirarchy they aren't used.
Quote:
1 tv's
2 cameras
3 Big Screens
4 Plasmas
5 digital
6 35mm
7 Smart Media
Add your categories to the heirarchy, root nodes should point back to themselves like this:
Quote:
1 1 -- tv's points to tv's, indicating a root node
2 2 -- same for cameras
then add to the heirarchies like this:
Quote:
3 1 -- point Big Screens to the tv's category
4 3 -- point Plasmas to the Big Screens category
5 2 -- point digital to the cameras category
6 2 -- point 35mm to the cameras category
7 5 -- point Smart Media to the digital category
Now to traverse the tree you need a couple of queries:
Code:
Select all root nodes:
SELECT cat_id FROM heirarchy WHERE cat_id = parent_id;

Select child nodes:
SELECT cat_id FROM heirarchy WHERE parent_id = ?
Using cat_id from the parent node as the only parameter.
Now in code, basically you want to build your root node list, then recursivley iterate through each node following the heirarchy. For each child node you read from your select statement, you have to call the "Select child nodes" query usings cat_id as the parent_id.

What can get really weird here is that there is nothing preventing you from adding the Smart Media category with a 35mm parent as well, and many times this is exactly what you want to do. However, there is also nothing preventing you from adding tv's to ameras and then cameras to TV's creating an infinite loop. These are all things that have to be done programatically and very carefully.

I hope this helps a bit. Don't give in, these kinds of features are really nice to have!
__________________
Scott
B4 09 BA 09 01 CD 21 CD 20 53 63 6F 74 74 24
sdeming is offline   Reply With Quote