[英]Filter v-for on results of mysql join query
我正在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函数,但未找到方法。
经过大量的抓挠之后,我目前正在进行两个查询以获取所需的内容,但认为必须有一种方法可以使用查询来完成所需的操作。
也许您可以将计算属性与array方法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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.