Implementing Recursive Comments in PHP/MySQL

后端 未结 6 1250
-上瘾入骨i
-上瘾入骨i 2020-12-18 09:11

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

6条回答
  •  一个人的身影
    2020-12-18 09:55

    I had to implement recursive comments too. I broke my head with nested model, let me explain why :

    Let's say you want comments for an article. Let's call root comments the comments directly attached to this article. Let's calls reply comments the comments that are an answer to another comment.

    I noticed ( unfortunately ) that I wanted the root comments to be ordered by date desc, BUT I wanted the reply comments to be ordered date asc !! Paradoxal !!

    So the nested model didn't help me to alleviate the number of queries.

    Here is my solution :

    Create a comment table with following fields :

    id
    article_id
    parent_id (nullable)
    date_creation
    email
    whateverYouLike
    sequence
    depth

    The 3 key fields of this implementation are parent_id, sequence and depth. parent_id and depth helps to insert new nodes.

    Sequence is the real key field, it's kind of nested model emulation.

    Each time you insert a new root comment, it is multiple of x. I choose x=1000, which basically means that I can have 1000 maximum nested comments (That' s the only drawback I found for this system, but this limit can easily be modified, it's enough for my needs now).

    The most recent root comment has to be the one with the greatest sequence number.

    Now reply comments : we have two cases : reply for a root comment, or reply for a reply comment.

    In both cases the algoritm is the same : take the parent's sequence, and retrieve one to get your sequence number. Then you have to update the sequences numbers which are below the parent's sequence and above the base sequence, which is the sequence of the root comment just below the root comment concerned.

    I don't expect you to understand all this since I'm not a very good explainer, but I hope it may give you new ideas. ( At least it worked for me better than nested model would= less requests which is the real goal ).

提交回复
热议问题