javascript - 寻找一种方法来获取从数据库查询返回的项目总数,用于与 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
解决方案
您必须从正在执行的查询中单独获得一个计数。先获取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")
推荐阅读
- c# - autoMapper 相关错误,在 lambda_method19(Closure , Head , Head , ResolutionContext )
- python - event.keycode 在 python 中不工作 tkinter
- amazon-web-services - 'cdk' 未被识别为内部或外部命令
- firebase - Firestore + Firebase 函数工作缓慢或返回太快
- html - 跨度内的垂直对齐不适用于特殊字符
- macros - 使用 doxygen 记录特殊宏
- database - 如何使用 Unity 创建和访问小型服务器?
- android - 删除 `jcenter()` Maven 存储库的使用
- acumatica - Acumatica - IN 错误:备用 ID 的值“TESTID”已用于另一个库存项目
- javascript - jQuery 表格视图更多/更少功能