Currently in the process of developing a project using Nuxt.js along with an express API and mysql database. Specifically, I am working on implementing comments functionality for a blog within the project. Each blog post can have multiple comments with potential replies to each comment. The data is stored in two separate tables named 'comments' and 'replies', where the 'replies' table has a foreign key relationship with the 'comments' table. To retrieve relevant information from the database, I utilize a JOIN query as follows:
SELECT * FROM comments LEFT JOIN replies ON comments.id = replies.comment_id;
This query returns a dataset structured like the following example:
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
| id | post_id | user_id | content | created_at | id | comment_id | reply_user_id | reply_content | reply_created_at |
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
| 1 | 1 | 1 | Well thats a very lovely post | 2018-11-24 19:29:05 | 1 | 1 | 2 | it is indeed | 2018-11-25 15:11:20 |
| 1 | 1 | 1 | Well thats a very lovely post | 2018-11-24 19:29:05 | 2 | 1 | 1 | why thanks | 2018-11-25 15:11:39 |
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
Now that I have successfully retrieved the necessary data, my goal is to present it efficiently. My initial attempt involves using 'v-for' to iterate through the data while avoiding duplication of the 'content' field. For instance:
<div v-for="comment in comments" :key="comment.reply_content">
<p>{{comment.content}}</p>
<p>{{comment.reply_content}}</p>
</div>
However, this approach results in displaying the same 'content' for each corresponding reply. To resolve this issue and display unique 'content' values alongside all relevant replies, I explored various JavaScript functions such as '.map()' and '.join()', but to no avail.
Although I resorted to executing two queries to achieve the desired outcome, I firmly believe there exists a more efficient solution utilizing the existing query structure.