如何使用 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
}

但我得到 { "总数": "11", "数据":[ { "计数":"11" } ] } ,如何在不写两次的情况下获取数据列表?我不想这样做:

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);

最新更新