javascript - 在 mysql 连接查询的结果上过滤 v-for

标签 javascript mysql express vue.js nuxt.js

我正在 Nuxt.js 中构建一个项目,该项目使用使用 mysql 数据库的快速 API。我在项目中有一个博客,正在为每篇博客文章设置评论,可以对每条评论进行回复。每个评论可以有多个回复。

我已经为这些设置了两个数据库表,'comments' 和 'replys',其中 'replys' 与 'comments' id 有一个 comment_id 外键关系。我使用这样的连接查询数据库:

SELECT * FROM comments LEFT JOIN responses 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 函数,但没有找到方法。

经过大量的摸索之后,我目前正在进行两个查询以获得我需要的东西,但我认为必须有一种方法来使用我必须做我需要做的查询。

最佳答案

也许您可以使用带有数组方法 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>

关于javascript - 在 mysql 连接查询的结果上过滤 v-for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464716/

相关文章:

mysql - 时间戳给出错误的结果

javascript - 嵌套 Promise 未推送到数组

javascript - 无法在本地主机中使用带有 expressJs api 的查询参数

javascript - 提交表单或模拟按下 Enter/Return

javascript - 如何修复 wp super 缓存错误消息?

php - 使用新表将 csv 加载到 MySQL 中

javascript - 使用 AJAX 部分更新列表

node.js - 文件上传在nodejs中不起作用

javascript - D3 从大 csv 创建条形图

javascript - 为 D3 堆叠条形图准备嵌套的 JSON 数据