Design database for category, subcategory and associated books

我的未来我决定 提交于 2019-11-30 23:45:01

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!