增量 —.increment(column, amount)
将列值增加指定的数量。支持对象语法column。
knex('accounts')
.where('userid', '=', 1)
.increment('balance', 10)
输出:
update `accounts` set `balance` = `balance` + 10 where `userid` = 1
knex('accounts')
.where('id', '=', 1)
.increment({
balance: 10,
times: 1,
})
输出:
update `accounts` set `balance` = `balance` + 10, `times` = `times` + 1 where `id` = 1
递减 —.decrement(column, amount)
将列值减少指定的数量。支持对象语法column。
knex('accounts').where('userid', '=', 1).decrement('balance', 5)
输出:
update `accounts` set `balance` = `balance` - 5 where `userid` = 1
knex('accounts')
.where('id', '=', 1)
.decrement({
balance: 50,
})
输出:
update `accounts` set `balance` = `balance` - 50 where `id` = 1
截断 -.truncate()
截断当前表。
knex('accounts').truncate()
输出:
truncate `accounts`
拔 -.pluck(id)
这将从结果的每一行中选择指定的列,从而产生一个承诺,该承诺将解析为所选值的数组。
knex.table('users').pluck('id').then(function(ids) { console.log(ids); });
首先 -.first([columns])
与select相似,但仅使用查询中的第一条记录进行检索和解析。
knex.table('users').first('id', 'name').then(function(row) { console.log(row); });
克隆 —.clone()
克隆当前查询链,可用于在不更改原始查询的情况下在其他查询中重用部分查询摘要。
修改 —.modify(fn, *arguments)
允许封装和重用查询片段和常见行为作为函数。回调函数应将查询构建器作为其第一个参数,然后再传递其余要修改的(可选)参数。
var withUserName = function(queryBuilder, foreignKey) {
queryBuilder.leftJoin('users', foreignKey, 'users.id').select('users.user_name');
};
knex.table('articles').select('title', 'body').modify(withUserName, 'articles_user.id').then(function(article) {
console.log(article.user_name);
});
columnInfo —.columnInfo([columnName])
返回一个具有当前表的列信息的对象,或者返回一个单独的列(如果已传递的话),并返回具有以下键的对象:* defaultValue:该列的默认值* 类型:列类型* maxLength:最大长度为column *设置 nullable:该列是否可以为null
knex('users').columnInfo().then(function(info) { // ... });
调试 -.debug([enabled])
覆盖当前查询链的全局调试设置。如果省略启用,将打开查询调试。
连接 —.connection(dbConnection)
该方法将数据库连接设置为用于查询,而不使用连接池。您应该向其传递与相应驱动程序返回的AcquisitionConnection()相同的对象
const Pool = require('pg-pool')
const pool = new Pool({ ... })
const connection = await pool.connect();
try {
return await knex.connection(connection); // knex here is a query builder with query already built
} catch (error) {
// Process error
} finally {
connection.release();
}
选项 -.options()
允许混入数据库客户端特定库定义的其他选项:
knex('accounts as a1')
.leftJoin('accounts as a2', function() {
this.on('a1.email', '<>', 'a2.email');
})
.select(['a1.email', 'a2.email'])
.where(knex.raw('a1.id = 1'))
.options({ nestTables: true, rowMode: 'array' })
.limit(2)
.then(...