接口.jianghuKnex
12003jianghuKnex 是一个基于 knex 的数据库查询和操作库,提供了简洁易用的 API,支持常规的 CRUD 操作、数据历史记录、事务处理和复杂连表查询。以下是 jianghuKnex 的常用操作:
- 查询:
select、first、count - 新增:
jhInsert - 更新:
jhUpdate - 删除:
jhDelete - 内连接:
innerJoin - 左连接:
leftJoin - 右连接:
rightJoin - 分页:
offset&limit - 事务处理:
transaction - ...更多操作 参考knex文档
jianghuKnex启用
在/config/config.local.js or /config/config.prod.js中配置knex信息,
框架会自动将knex和jianghuKnex挂载到 this.app上。
{knex: {client: {dialect: 'mysql',connection: {host: '127.0.0.1',port: 3306,user: 'root',password: '123456',database: 'test01'},pool: { min: 0, max: 10 },acquireConnectionTimeout: 30000},app: true}}
jianghuKnex使用
jianghuKnex 在原有 knex 的基础上进行了扩展,提供了一些额外的功能。以下是一些常用操作及示例代码:
查询
select:查询返回列表const list = await this.app.jianghuKnex("student").where({ gender: 'male' }).select();this.app.logger.info('jianghuKnexExample.js select()', '=====>',`result length: ${list.length}`);
first:查询返回第一个结果const student = await this.app.jianghuKnex("student").where({ studentId: 'S10001' }).first();this.app.logger.info('jianghuKnexExample.js first()', '=====>', { studentId: student?.studentId, name: student?.name });
count:查询数量const countResult = await this.app.jianghuKnex("student").where({}).count('* as count').first();this.app.logger.info('jianghuKnexExample.js count()', '=====>', countResult);
新增
jhInsert:新增数据。const student = { studentId: 'T00001', name: '测试001' };await this.app.jianghuKnex("student", this.ctx).jhInsert(student);this.app.logger.info('jianghuKnexExample.js jhInsert()', '=====>', student);
更新
jhUpdate:更新现有数据const student = { studentId: 'T00001', name: '测试同学001' };await this.app.jianghuKnex("student", this.ctx).where({ studentId: student.studentId }).jhUpdate({ name: student.name });this.app.logger.info('jianghuKnexExample.js jhUpdate()', '=====>', student);
删除
jhDelete:删除数据const student = { studentId: 'T00001' };await this.app.jianghuKnex("student", this.ctx).where({ studentId: student.studentId }).jhDelete({ name: student.name });this.app.logger.info('jianghuKnexExample.js jhDelete()', '=====>', student);
连表查询
innerJoin: 内连接leftJoin: 左连接rightJoin: 右连接const classId = '2021-01级-01班';const list = await this.app.jianghuKnex("class", this.ctx).leftJoin('student', 'class.classId', 'student.classId').whereRaw('class.classId = ?', [classId]).select();this.app.logger.info('jianghuKnexExample.js leftJoin()', '=====>', `result length: ${list.length}`);
分页查询
offset: 第几页limit: 每页多少条数据const pageSize = 5;const pageNumber = 1;const list = await this.app.jianghuKnex("student").offset((pageNumber - 1) * pageSize).limit(pageSize).select();this.app.logger.info('jianghuKnexExample.js offset()', '=====>',`result length: ${list.length}`);
数据历史
jianghuKnex('student', this.ctx), 在传入 this.ctx 后,jianghuKnex 会自动记录本次操作记录 同时 也会记录数据历史:
- 操作记录
- 当前表.
operationByUserId:操作者的 userId。 - 当前表.
operationByUser:操作者的用户名。 - 当前表.
operationAt:操作发生的时间。
- 当前表.
- 数据历史:
_record_history里记录了数据历史, 可以通过使用jianghu-init tool --type=record-history-page工具,您可以生成查看 数据历史页面,以便查看历史变动。
事务
jianghuKnex 支持事务处理,以确保数据操作的一致性和完整性。事务可以确保一组操作要么全部成功执行,要么全部失败回滚。要使用事务,您可以使用框架提供的 transaction 方法。
const student = { studentId: 'T00002', name: '测试002' };const classObj = { classId: '2021-07级-01班', className: '七年级一班' };await this.app.jianghuKnex.transaction(async trx => {// 删除await trx('student', this.ctx).jhDelete(student);await trx('class', this.ctx).jhDelete(classObj);// 新增await trx('student', this.ctx).jhInsert(student);await trx('class', this.ctx).jhInsert(classObj);});this.app.logger.info('jianghuKnexExample.js transaction()', '=====>', classObj);
测试表
CREATE TABLE `class` (`id` int(11) NOT NULL AUTO_INCREMENT,`classId` varchar(255) DEFAULT NULL COMMENT '班级ID',`className` varchar(255) DEFAULT NULL COMMENT '学生状态',`remarks` mediumtext COMMENT '备注',`operation` varchar(255) DEFAULT 'insert' COMMENT '操作; insert, update, jhInsert, jhUpdate, jhDelete jhRestore',`operationByUserId` varchar(255) DEFAULT NULL COMMENT '操作者userId',`operationByUser` varchar(255) DEFAULT NULL COMMENT '操作者用户名',`operationAt` varchar(255) DEFAULT NULL COMMENT '操作时间; E.g: 2021-05-28T10:24:54+08:00 ',PRIMARY KEY (`id`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=175 DEFAULT CHARSET=utf8mb4;CREATE TABLE `student` (`id` int(11) NOT NULL AUTO_INCREMENT,`studentId` varchar(255) DEFAULT NULL COMMENT '学生ID',`name` varchar(255) DEFAULT NULL COMMENT '学生名字',`gender` varchar(255) DEFAULT NULL COMMENT '性别',`dateOfBirth` varchar(255) DEFAULT NULL COMMENT '出生日期',`classId` varchar(255) DEFAULT NULL COMMENT '班级ID',`level` varchar(255) DEFAULT NULL COMMENT '年级',`bodyHeight` varchar(255) DEFAULT NULL COMMENT '身高',`studentStatus` varchar(255) DEFAULT NULL COMMENT '学生状态',`remarks` mediumtext COMMENT '备注',`operation` varchar(255) DEFAULT 'insert' COMMENT '操作; insert, update, jhInsert, jhUpdate, jhDelete jhRestore',`operationByUserId` varchar(255) DEFAULT NULL COMMENT '操作者userId',`operationByUser` varchar(255) DEFAULT NULL COMMENT '操作者用户名',`operationAt` varchar(255) DEFAULT NULL COMMENT '操作时间; E.g: 2021-05-28T10:24:54+08:00 ',PRIMARY KEY (`id`) USING BTREE,KEY `studentId` (`studentId`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
数据隔离
多应用共用一个数据库时,每个应用之间数据隔离,更新参考多应用-jhId
enable: 是否开启jhId: 数据隔离的标记careTableViewList: 采用数据隔离的表jianghuConfig:{jhIdConfig: {enable: false,jhId: 'project01',careTableViewList: [ 'class', 'student' ],},}