Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create nested categories in a Database?

I am making a videos website where categories will be nested:

e.g. Programming-> C Language - > MIT Videos -> Video 1 Programming -> C Language -> Stanford Video - > Video 1 Programming -> Python -> Video 1

These categories and sub-categories will be created by users on the fly. I will need to show them as people create them in the form of a navigable menu, so that people can browse the collection easily.

Could someone please help me with how I can go about creating such a database?

like image 678
MathOldTimer Avatar asked May 29 '09 14:05

MathOldTimer


1 Answers

Make a categories table with the following fields:

  • CategoryID - Integer
  • CategoryName - String/Varchar/Whatever
  • ParentID - Integer

Your ParentID will then reference back to the CategoryID of its parent.

Example:

CategoryID CategoryName ParentID
---------------------------------
1          Dog          NULL
2          Cat          NULL
3          Poodle       1
4          Dachsund     1
5          Persian      2
6          Toy Poodle   3
like image 66
TheTXI Avatar answered Nov 11 '22 12:11

TheTXI