Design database for category, subcategory and associated books

我的未来我决定 提交于 2019-11-30 18:17:12

问题


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 structure a database for a category that can have books and a subcategory which can also have books?

I have already design a database, but am not convinced by the approach. So I would really appreciate if the guys with experience gave me some advice or improvement or a completely different approach.

This how my tables look like (bare in mind this is not the actual code)

TABLE Category
    ID
    user_id -- Foreign key from user
    name

TABLE SubCategory
    ID
    user_id
    category_id
    name

The table for the book have the same design.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/29198559/design-database-for-category-subcategory-and-associated-books

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