Codementor Events

Nested comment database model

Published Aug 23, 2018

Hello, I want to build a comment system for my posts. For now it will be one level deep only, means comment and its reply. After reading various article on web, there is 2 suggested way to make your table structure.

1. Using two tables

-id
-post_id
-user_id
-comment
-created_at
-updated_at
-deleted_at -id
-comment_id
-user_id
-comment
-created_at
-updated_at
-deleted_at

and then “one to many relationship” between these 2 tables. Now the second approach

2. Using one table

-id
-post_id
-user_id
-comment
-parent_id -created_at
-updated_at
-deleted_at

In this second approach, for top-level comment, parent_id can be set NULL .

What is your suggested way to do this?

I think the first one is more normalized version while the second one gives me the flexibility of increasing the replies nested level in future, So for any reason if I plan to increase the level of nesting for comment system I do not have to change database structure anymore.

Table Structure for Nested Comments

View all posts by kuldeepluvani

Discover and read more posts from Kuldeep Luvani
get started
post commentsBe the first to share your opinion
Show more replies