我正在尝试使用Knex进行简单计数(因为似乎Bookshelf尚未支持该功能)。以下代码是有效的:
bookshelf.knex('hosts').count('id').then(function(total) {
res.send({
meta: {
total: total[0]['count(`id`)']
}
});
});
我觉得很奇怪,为什么要写total[0]['count('id')']
才能得到实际的结果。请问我的做法对吗?
谢谢!
我正在尝试使用Knex进行简单计数(因为似乎Bookshelf尚未支持该功能)。以下代码是有效的:
bookshelf.knex('hosts').count('id').then(function(total) {
res.send({
meta: {
total: total[0]['count(`id`)']
}
});
});
我觉得很奇怪,为什么要写total[0]['count('id')']
才能得到实际的结果。请问我的做法对吗?
谢谢!
所有来自knex.js的结果都是数组。一个查询可能成功,但只返回0个结果。
此外,您可以直接在列名(或count()
调用)中使用别名。就像这样:
bookshelf.knex('hosts').count('id as CNT').then(function(total) {
res.send({
meta: {
total: total[0].CNT
}
});
});
仍然需要获取第一个元素,但是您可以将该列引用为普通的JSON属性。
虽然 knex 返回的结果是数组,但它也有一种返回第一个结果的方法,该方法将返回一个对象,而非数组。可以很容易地在不需要依赖 [0] 或任何其他访问数组中计数的方式的前提下直接获取计数。对于您的示例,更简洁的解决方案可能是:
bookshelf
.knex("hosts")
.count("id")
.first()
.then(function(total) {
res.send({
meta: {
total: total.count
}
});
});
Node.js 代码
let result = await knex.count("id").from('events').first();
if (result) {
console.log(result.count);
}
这似乎正常工作,而且更简单一些
knex('Quotes').count('quoteBody')
.then((res)=>{
//console.log("rows "+JSON.stringify(res))
console.log("rowspl2 "+res[0]['count(`quoteBody`)'])
})
.catch((err)=>{
console.log("err "+err)
})
或者尝试这样做
knex('Quotes').count('quoteBody', {as: 'rows'})
.then((res)=>{
// console.log("rows "+JSON.stringify(res))
console.log("rowsp "+res[0]['rows'])
})
.catch((err)=>{
console.log("err "+err)
})
count("col")
的SQL查询中,通常会返回一个名为“count”的列(可以别名),其中包含一行结果。由于Knex围绕SQL构建,因此查询始终返回对象数组(行),其属性与列匹配。.count()
或其他聚合器可能会特殊处理以返回单个值,但实际上它们只是聚合器,您可以在同一查询中使用几个聚合器(甚至.groupBy()
不同的列,在这种情况下,您将拥有与组相同数量的行,每个组都有自己的计数)。 - clayknex.raw
,例如knex.raw('sum(case when "column1" = \'someValue\' then 1 else 0 end) as "total"')
。 - claywhere
、on
和其他条件特性;knex.raw
确实是为特殊情况而设,但基本过滤不是一个理由。 - Kalnode