How can I model this class in a database?

后端 未结 4 1629
猫巷女王i
猫巷女王i 2020-12-12 02:33

I need a little of help. This is my design to organize several categories.

   Category 1
     Sub Category 1.1
       Sub Category 1.1.1
     Sub Category 1.         


        
4条回答
  •  猫巷女王i
    2020-12-12 03:29

    You'd have a table something like this:

    • category
      • id (primary key, not null)
      • name (text, not null)
      • parent_category_id (foreign key to category.id, nullable)

    Then, if a category has a parent, you reference the id of that other row. So the table is self-referential. Toplevel categories have a null parent_category_id.

    When building tables like this you do need to be careful that you don't create a circular reference.

提交回复
热议问题