V
V
vopross2017-01-19 23:25:59
PHP
vopross, 2017-01-19 23:25:59

How to correctly display comments with a post?

People tell me the best way to store comments in the database and display them in the list along with the entry. A banal example of Instagram or VK, when several comments are placed in the list under the entry.
Entry
3 comments
Entry
3 comments
Entry
3 comments
Etc.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Tikhomirov, 2017-01-21
@vopross

The most elegant solution, so that, as in the variant above, not to pull a bunch of comments for each entry (because you can imagine how many requests there will be if there are, for example, 20 entries on the page, each of which has 10-20 comments added) is that you need to create a `parent` column in the table and enter one there if the comment is added from the input field of a new record, otherwise, if it is 0 from the field opened by the "Reply" link. This will essentially mean the answer to the parent comment, which is a record on the wall (because what is not a record? There is a text, there is a picture). When displaying comments, simply display posts with the value `parent` = 1 using another template, for example comment_parent.htm, if you have your own template engine - such as with a gray background, larger text, etc. And comments - comments_answer.htm. In the database, create a `thread_id` column, where you enter the `id` of the comment, if it is a post, and it, when adding a comment to it, simply getting the `thread_id` of the parent comment. And most importantly, when outputting, sort them by thread_id and comment id at the same time:

... AND `position` <= "3"
ORDER BY `thread_id` DESC, `id` ASC
LIMIT 0,20

This will help to group them in the right order, and without resorting to GROUP BY, displaying, in addition to the entry itself, the last three comments to it. I wrote impromptu, implemented it relatively long ago, omitted the details, but the main thing is that I conveyed the essence. With certain skills and, most importantly, an understanding of the essence, this is all implemented relatively simply. For this, I have outlined the very essence, so that you understand the principle itself. And the implementation is carried out specifically for the project.

V
vetsmen, 2017-01-20
@vetsmen

Create two tables - with news and with comments.
When you create news, initialize its ID.
When entering a comment into the table, also enter the ID of the news to which it belongs.
Then, when you go through the cycle, take the ID of the news and run it through the table with comments, if you find a match, output it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question