我正在Nuxt.js中构建一个项目,该项目使用一个使用MySQL数据库的Express API。我在该项目中有一个博客,正在为每个可以回复每个评论的博客帖子设置评论。每个评论可以有很多回复。
我为这些数据库设置了两个数据库表,“ comments”和“ replys”,其中“ replys”具有带有“ comments” ID的comment_id外键关系。我使用这样的联接查询数据库:
SELECT * FROM comments LEFT JOIN replys ON comments.id = replys.comment_id;
返回如下响应:
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
| 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 |
+----+---------+---------+-------------------------------+---------------------+----+------------+---------------+---------------+---------------------+
因此它正在获取我需要的所有数据,我现在只需要使用它。我想做的是使用v-for来遍历数据,但没有重复的“内容”,所以像这样:
<div v-for="comment in comments" :key="comment.reply_content">
<p>{{comment.content}}</p>
<p>{{comment.reply_content}}</p>
</div>
但是,这当然会显示它具有的每个回复的comment.content。所以我想将其限制为唯一的comment.content,同时仍显示所有答复。我尝试查看.map()和.join()之类的javascript函数,但没有找到方法。
在抓了很多头之后,我目前正在进行两个查询以获取所需信息,但认为必须有一种方法可以使用查询来完成所需的操作。
答案 0 :(得分:0)
也许您可以将计算属性与数组方法reduce
一起使用来对注释进行排序。.
computed: {
sortedComments() {
return this.comments.reduce((cum, next) => {
const lastCommentArray = cum[cum.length - 1]
if (cum.length == 0 ||
next.content != lastCommentArray[lastCommentArray.length - 1].content) {
cum.push([])
}
cum[cum.length - 1].push(next)
return cum
}, [])
}
}
然后您可以像这样遍历它..
<div v-for="commentArray in sortedComments" :key="commentArray[0].content">
<p>{{commentArray[0].content}}</p>
<p v-for="reply in commentArray" :key="reply.reply_content">{{reply.reply_content}}</p>
</div>