Sequelize是一个基于Promise的Node.js ORM,它具有强大的事务支持,关联关系,预读和延迟加载,读取复制等功能。
更多操作方法,请参考官方文档:https://eggjs.org/zh-cn/tutorials/sequelize.html
安装egg-sequelize以及mysql2
在config/plugin.js中引入egg-sequelize插件
exports.sequelize = { enable: true, package: 'egg-sequelize' };
config.sequelize = { dialect: 'mysql', host: '127.0.0.1', port: 3306, database: 'bank', username: 'root', password: "123456" };
注意:如果define中的是user,我们定义的数据表要是users,也就是说需要是复数形式。
'use strict'; module.exports = app => { const { STRING, INTEGER, DATE } = app.Sequelize; const User = app.model.define('user', { id: { type: INTEGER, primaryKey: true, autoIncrement: true }, username: STRING(30), age: INTEGER, sex: STRING(30), created_at: DATE, updated_at: DATE, }); return User; };
// 增加数据 async create() { const user = await this.ctx.model.User.create({username: "张三",age: 20}); this.ctx.body = user; }
更多其他的查询方法,请查看官方文档:https://www.sequelize.com.cn/core-concepts/model-querying-finders
// 查询数据 async query() { const userList = await this.ctx.model.User.findAll(); this.ctx.body = userList; }
// 查询指定字段的数据 const userList = await this.ctx.model.User.findAll({attributes: ['id','username']});
const userList = await this.ctx.model.User.findAll({where: {"id": 2}});
const userList = await this.ctx.model.User.findAll({order: [['id', 'ASC']]});
async update() { // 根据主键修改 const user = await this.ctx.model.User.findByPk(2); user.update({"username": "秦二世","age": 10}); this.ctx.body = "修改成功" }
async delete() { const data = await this.ctx.model.User.findByPk(2); if (!data) { this.ctx.state = 404; return; } data.destroy(); this.ctx.body = "删除成功"; }