簡體   English   中英

尋找一種方法來獲取從數據庫查詢返回的項目總數,以便與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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM