Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Recursive Comments in PHP/MySQL

I'm trying to write a commenting system, where people can comment on other comments, and these are displayed as recursive threads on the page. (Reddit's Commenting system is an example of what I'm trying to achieve), however I am confused on how to implement such a system that would not be very slow and computationally expensive.

I imagine that each comment would be stored in a comment table, and contain a parent_id, which would be a foreign key to another comment. My problem comes with how to get all of this data without a ton of queries, and then how to efficiently organize the comments into the order belong in. Does anyone have any ideas on how to best implement this?

like image 272
GSto Avatar asked Dec 30 '22 00:12

GSto


1 Answers

Try using a nested set model. It is described in Managing Hierarchical Data in MySQL.

The big benefit is that you don't have to use recursion to retrieve child nodes, and the queries are pretty straightforward. The downside is that inserting and deleting takes a little more work.

It also scales really well. I know of one extremely huge system which stores discussion hierarchies using this method.

like image 178
Seth Avatar answered Dec 31 '22 12:12

Seth