简体   繁体   English

寻找一种方法来获取从数据库查询返回的项目总数,以便与knex一起使用

[英]Looking for a way to get a total count of items returned from a database query, for use in pagination with knex

I am currently adding pagination to my back-end models for retrieving articles from a database using knex. 我目前正在为我的后端模型添加分页,以便使用knex从数据库中检索文章。 The model has a limit and an offset, but i need to get hold of the total count of rows returned before limit and offset are applied. 该模型有一个限制和一个偏移量,但我需要保持在应用限制和偏移之前返回的总行数。

I have considered using a separate model to get a count of the articles, but it seems unnecessary. 我考虑使用一个单独的模型来计算文章,但似乎没必要。

  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

You do have to get a count seperately from the query you are executing. 您必须从正在执行的查询中单独计算。 Get the count first, and then run the query again with the limit and offset to get the records 首先获取计数,然后使用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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM