knex.js

安装

Knex可以在Node.JS和浏览器中用作SQL查询构建器,Knex的主要目标环境是Node.js,您需要安装knex库,然后安装相应的数据库库

$ npm install knex --save
$ npm install mysql
1
2

初始化

knex模块本身就是一个函数,它接受Knex的配置对象,接受一些参数。该client参数是必需的,用于确定将与库一起使用的客户端适配器。

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
})
1
2
3
4
5
6
7
8
9

knex查询器

图书馆的心脏,knex查询生成器是用于构建和执行标准的SQL查询,如selectinsertupdatedelete

where(哪里)

通过where查找到条件指定的内容

knex('users').where('id', 1)
输出:
select * from `users` where `id` = 1
1
2
3

whereNot(哪里没有)

查找表中是否有条件中的值

knex('users').whereNot({
  first_name: 'Test',
  last_name:  'User'
}).select('id')
输出:
select `id` from `users` where not `first_name` = 'Test' and not `last_name` = 'User'
1
2
3
4
5
6

join(table, first, [operator], second) 加入方法

连接构建器可用于指定表之间的连接,第一个参数是连接表,后三个参数分别是第一个连接列,连接操作符和第二个连接列。

knex('users')
  .join('contacts', 'users.id', '=', 'contacts.user_id')
  .select('users.id', 'contacts.phone')
输出:
select `users`.`id`, `contacts`.`phone` from `users` inner join `contacts` on `users`.`id` = `contacts`.`user_id`
1
2
3
4
5

clearSelect() 清除方法

clearSelect()清除查询中的所有select的项目,不包括子查询

knex.select('email','name').from('users').clearSelect()
输出:
select*from'users'
1
2
3

clearWhere()清除查询中所有where的项目,不包括子查询

knex.select('email', 'name').from('users').where('id', 1).clearWhere()
输出:
select `email`, `name` from `users`
1
2
3

orderBy () 排序

向查询添加order by子句。对获取到的数据进行排序。

knex('users').orderBy('name', 'desc')//倒序
输出:
select * from `users` order by `name` desc
1
2
3

insert () 插入方法

创建一个插入查询,将要插入到行中的属性的哈希值或插入数组作为单个插入命令执行。

knex('books').insert({title: 'Slaughterhouse Five'})
输出:
insert into `books` (`title`) values ('Slaughterhouse Five')
1
2
3

offset(value) 偏移

创建一个便宜查询,设置偏移量从第几个开始

knex.select('*').from('users').offset(10)
1

12345678901 from 1

limit(value) 限制

向查询添加限制数量

knex.select('*').from('users').limit(10).offset(30)
1

count(column|columns|raw, [options])计数

对指定的列或列数组执行计数,从count(和其他聚合查询)返回的值是一个对象数组

knex('users').count('active')
输出:
select count(`active`) from `users`
1
2
3

update(params)更新

创建更新查询,根据其他查询约束更新属性哈希值或键/值对。如果传递返回的数组,例如['id','title'],则它会解析promise /使用包含指定列的所有更新行的数组来完成回调。

edit(id, params ){
    return knex(this.table).where('id', '=', id).update( params )
}
1
2
3

increment(column, amount)增量

按列指定的数量增加列值。支持对象语法column

knex('accounts')
  .where('userid', '=', 1)
  .increment('balance', 10)
输出:
update `accounts` set `balance` = `balance` + 10 where `userid` = 1
1
2
3
4
5