node.js - 如何使用 knex.js 从数据库中获取一页数据列表和总数?
问题描述
我有一个包含一些记录(例如 100 条)的用户表,当存在某些 where 条件时,如何从中获取一页数据和总计数?
我尝试了以下方法:
var model = knex.table('users').where('status',1).where('online', 1)
var totalCount = await model.count();
var data = model.offset(0).limit(10).select()
return {
totalCount: totalCount[0]['count']
data: data
}
但我得到 { "totalCount": "11", "data": [ { "count": "11" } ] } ,我怎样才能得到 dataList 而不写两次?我不想这样做:
var totalCount = await knex.table('users').where('status',1).where('online', 1).count();
var data = await knex.table('users').where('status',1).where('online', 1).offset(0).limit(10).select()
return {
totalCount: totalCount[0]['count']
data: data
}
谢谢 :)
解决方案
您可能应该使用更高级别的库,例如 Objection.js,它已经具有获取页面和总数的便捷方法。
您可以使用 knex 执行此操作:
// query builder is mutable so when you call method it will change builders internal state
const query = knex('users').where('status',1).where('online', 1);
// by cloning original query you can reuse common parts of the query
const total = await query.clone().count();
const data = await query.clone().offset(0).limit(10);
推荐阅读
- android-studio - 在android studio上的数据库java中插入用户信息
- selenium - JetBrains Datalore 上的 Selenium with Chrome
- r - source() 函数阻止读取下游函数
- node.js - 复选框中的函数 onChangeAnswers 他做了什么
- r - 使用将方程应用于参考表的函数填充数据框列
- python-3.x - CoinbaseProAPI/CBpro。验证。网络套接字。不应该这么难吗?
- r - 最后一位数字上的单独列
- scheduled-tasks - 在 Windows 10 的任务计划程序中完成另一个服务后启动服务
- skiasharp - SkiaSharp XPS DrawBitMap 正在剪裁?
- mongodb - 无法连接到 Docker 中的数据库主机