Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the algorithm behind nested comments?

I want to learn the comment displaying algorithm behind Reddit. How is a comment related with its child and so on? How they are stored in the database?

Lets say

comment1
-comment2
--comment3
-comment4
--comment5
--comment6
---comment7
----comment8
comment9

How to display comment5 which is after comment4 which is after comment1? What is the idea behind this sequencing? And how to relate them in the database?

like image 318
ilhan Avatar asked Jan 22 '26 01:01

ilhan


1 Answers

It is called hierarchy. Each comment either has no parent comment, or has one parent comment. This way you can display every "top level" comment (thanks to the fact they have no parent comments), then child comments for each of them etc. etc.

And the database structure may look like this for comments table:

  • id field identifying single comment,
  • parent_id being set to parent's ID or not set (set to NULL or set to 0),
  • created - timestamp for comment creation,
  • content - actual comment content,
  • any additional field you need,
like image 110
Tadeck Avatar answered Jan 23 '26 15:01

Tadeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!