首页 > 解决方案 > 如何使用 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
}

谢谢 :)

标签: node.jsknex.js

解决方案


您可能应该使用更高级别的库,例如 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);

推荐阅读