I have a cms which stores comments against articles. These comments can be both threaded and non threaded. Although technically they are the same just with the reply column
I really like how Drupal solves this problem. It assigns a thread id to each comment. This id starts at 1 for the first comment. If a reply is added to this comment, the id 1.1
is assigned to it. A reply to comment 1.1
is given the thread id 1.1.1
. A sibling of comment 1.1
is given the thread id 1.2
. You get the idea. Calculating these thread ids can be done easily with one query when a comment is added.
When the thread is rendered, all of the comments that belong to the thread are fetched in a single query, sorted by the thread id. This gives you the threads in the ascending order. Furthermore, using the thread id, you can find the nesting level of each comment, and indent it accordingly.
1
1.1
1.1.1
1.2
1.2.1
There are a few issues to sort out:
Drupal solves the first issue in a more complicated way using a numbering system called vancode. As for the second issue, it is solved by appending a backslash (whose ASCII code is higher than digits) to thread ids when sorting by descending order. You can find more details about this implementation by checking the source code of the comments module (see the big comment before the function comment_get_thread).