首页 > 解决方案 > 寻找一种方法来获取从数据库查询返回的项目总数,用于与 knex 进行分页

问题描述

我目前正在为我的后端模型添加分页,以便使用 knex 从数据库中检索文章。该模型有一个限制和一个偏移量,但我需要掌握在应用限制和偏移量之前返回的总行数。

我曾考虑使用单独的模型来计算文章数量,但这似乎没有必要。

  return connection
    .select(
      "articles.author",
      "articles.title",
      "articles.article_id",
      "articles.topic",
      "articles.created_at",
      "articles.votes"
    )
    .count({ comment_count: "comments.article_id" })
    .from("articles")
    .leftJoin("comments", "articles.article_id", "comments.article_id")
    .groupBy("articles.article_id")
    .orderBy(sort_by || "created_at", order || "desc")
    .limit(limit || 10)
    .offset((p - 1) * (limit || 10))
    .modify(query => {
      if (username) query.where("articles.author", username);
      if (topic) query.where("articles.topic", topic);
    });
};```

Expect to add a total_count property

标签: javascriptknex.js

解决方案


您必须从正在执行的查询中单独获得一个计数。先获取count,再用limit和offset再次运行查询获取记录

connection
.select(
  "articles.author",
  "articles.title",
  "articles.article_id",
  "articles.topic",
  "articles.created_at",
  "articles.votes"
)
.count({ comment_count: "comments.article_id" })
.from("articles")
.leftJoin("comments", "articles.article_id", "comments.article_id")
.groupBy("articles.article_id")
.orderBy(sort_by || "created_at", order || "desc")

推荐阅读