egg-sequelize配置(有model方案)+CRUD操作+事务
-
进入项目目录,打开命令行
-
安装egg-sequelize和mysql2数据库插件
cnpm install egg-sequelize mysql2 -S
-
-
找到
config/plugin.js-
添加下面的内容来开启插件
sequelize: { enable: true, package: 'egg-sequelize' },
-
-
配置数据库信息
-
找到
config/config.default.js -
对于单个数据库
config.sequelize = { dialect: "mysql", host: "127.0.0.1", port: "3306", user: "root", password: "123456", database: "book_list" //可选debug参数为true,可后台打印出数据库原生执行语句 } -
对于多个数据库
config.sequelize = { datasources: [ { delegate:"model", baseDir:"model", database:"biz", //加上其他公共信息 }, { delegate:"adminModel", baseDir:"admin_model", database:"admin", //加上其他公共信息 } ] }- 在model目录内的文件中,用app.model.define
- 在admin_model目录内的文件中,用app.adminModel.define
-
-
app目录内
-
打开后,在里面新建
user.js,添加内容为:module.exports = app => { const { STRING, INTEGER, DATE} = app.Sequelize; //定义数据表结构 const User = app.model.define('user',{ login: STRING, name: STRING(30), age: INTEGER, last_sign_in_at: DATE, created_at: DATE, updated_at: DATE, }); //定义查询接口函数 User.findByLogin = async function(login){ return await this.findOne({ where: { login: login } }); } //定义原型方法 User.prototype.logSignin = async function() { return await this.update({ last_sign_in_at: new Date() }); } return User; }; -
在
user控制器内使用- 调用接口函数,找到一个user
const user = await this.ctx.model.User.findByLogin(this.ctx.params.login); - 找到后,再调用自身原型方法
await user.logSignin()
- 调用接口函数,找到一个user
egg-sequelize的CRUD操作
-
create创建并保存实例const hello = await this.ctx.model.Book.create({ title: 'Hello World' });-
等价于
Model.build()创建 +instance.save()保存 -
转成json再输出控制台
console.log(hello.toJSON())
-
-
save保存更新实例const hello_old = await this.ctx.model.Book.finAll({ title: 'Hello World' }); hello_old.title = "newValue"; await hello_old.save({ fields: ['title'] })- 可设置只更新title这一列
-
delete删除实例const hello_old = await this.ctx.model.Book.create({ title: 'Hello World' }); await hello_old.destroy() -
重载实例
- 只要不save更新,则重载后还是原值
const hello = await this.ctx.model.Book.finAll({ title: 'Hello World' }); hello_old.title = "newValue"; const hello_twice = await this.ctx.model.Book.finAll({ title: 'Hello World' }); -
increment和decrement递增递减实例某列数字- 单个递增2
await hello.increment('age', { by: 2 }); - 多个递增
await hello.increment({ 'age': 2, 'cash': 100 });
- 单个递增2
-
count统计次数const result = this.ctx.model.Book.count({ author: 'fengmk2', }); -
max,min获取实例某列的最大或最小值const result = this.ctx.model.Book.max({ 'age' }); -
sum获取实例的某列总和const result = this.ctx.model.Book.sum({ 'age' });
egg-sequelize数据库事务
-
手动控制
const t = await sequelize.transaction(); try { // 第一步操作 // 第二步操作 await t.commit(); // 提交事务 } catch (err) { // error, rollback await t.rollback(); // 一定记得捕获异常后回滚事务!! throw err; } -
自动控制(不用自己提交,捕获回滚,报错)
-
要给操作加上第二个参数,值是{ transaction: t }
try{ const result = await sequelize.transaction(async t => { const user = await User.create({ firstName: 'Abraham', lastName: 'Lincoln' }, { transaction: t }); // 第一步操作 // 第二步操作 return xxx }); 执行到这里代表事务成功,result值则为里面返回的结果 } catch (err){ } -
如果成功后,还是想回滚,那就自己抛出错误
throw new Error();
-