Design database for category, subcategory and associated books

后端 未结 2 1515
孤独总比滥情好
孤独总比滥情好 2021-01-06 14:38

I know there has been a few answer to a couple of questions similar to the one am asking. But their approach didn\'t look convincing.

My question is how would I stru

相关标签:
2条回答
  • 2021-01-06 15:12

    There's no reason to have more than one table for "categories", whether it be a top-level category or a sub-category. They're all just "categories".

    So, have a single table called "categories", with a parent_id field:

    // categories table
    id
    name
    user_id
    parent_id
    

    When you want to pull all top level categories, just run your query against the categories table with a condition that parent_id is null.

    Then, when you want to pull sub categories, just run the query against the categories table with a condition that parent_id = 123 (or whatever).

    Not only does this keep everything a lot cleaner, but it also allows for expansion in case you want to continue adding sub-sub-sub-sub categories...etc.


    Another option is to use CakePHP's TreeBehavior.

    I personally just rather use the way I suggested above, but might just be because I haven't taken the time to really understand this behavior enough.

    0 讨论(0)
  • 2021-01-06 15:29

    If parent_category is null then it is a top level. If it is non-null then it is a sub category.

    TABLE Category
      ID
      name
      parent_category
    
    0 讨论(0)
提交回复
热议问题