Domanda

I am stuck with a design decision. It seems that the answer on my question always depends on the specific situation. Here is my situation:

In my relational database I have a category and sub_category tables already. You can make posts and comments that are either linked to the category or sub_category.

Is it wise to have one posts and one comments table in my database and include a 'type' field in the comment and post tables to distinguish if the post/comment belongs to a category or a sub_category.

Or is it better to split the post and comment tables up into a category_post/category_comment and sub_category_post/sub_category_comment tables?

I am looking for the solution that will optimise speed. I am also looking to follow an architecture pattern that is scalable due to the fact that posts and comments can grow in size quite quickly.

Thanks

È stato utile?

Soluzione

The first one, definitely: one posts table and one comments table. I would give each of them a category_id field and a subcategory_id field, so each can link to a category and/or subcategory. I don't think you need the type field.

I'd be tempted to simplify it further and not even have a seperate table for subcategories: instead, make category be a "tree" type model, ie have a category_id field in categories, so categories can be nested. Then you can have a) more than one level of nesting of categories, which is likely to be a requirement at some point and b) have a situation where there's no logical difference between a category and subcategory, other than that defined in the data (ie how they have been nested), which makes your app simpler (and simple = good).

So:

#fields - category_id
Post
  has_many :comments
  belongs_to :category

#fields - post_id, category_id
Comment
  belongs_to :post
  belongs_to :category  

#fields - parent_id
Category
  has_many :posts
  has_many :comments
  belongs_to :parent, :class_name => "Category", :foreign_key => :parent_id
  has_many :children, :class_name => "Category", :foreign_key => :parent_id
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top