寻找一种方法来获取从数据库查询返回的项目总数,用于 knex 的分页

Looking for a way to get a total count of items returned from a database query, for use in pagination with 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

您必须从正在执行的查询中单独获取计数。先获取计数,再运行再次查询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")