(写得不对的地方,请多提宝贵意见)
$ npm i egg-init -g
$ egg-init egg-example --type=simple
$ cd egg-example
$ npm i
不懂可以转至这里 https://eggjs.org/zh-cn/intro/quickstart.html
npm install --save egg-sequelize mysql2
config/plugin.js
中引入 egg-sequelize 插件)exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
config/config.default.js
中添加 sequelize 配置)module.exports = appInfo => {
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1535885709032_3135';
// add your config here
config.middleware = [];
// !!!!!添加的配置信息在这里 [Begin]!!!!!!
config.sequelize = {
dialect: 'mysql',
host: '127.0.0.1',
port: 3306,
database: '你的数据库名称',
username: '数据库用户名',
password: '数据库密码,倘若为空密码则填写 null'
}
// !!!!!添加的配置信息在这里 [End]!!!!!!
return config;
};
在 /app的目录下 建立 model文件夹,然后在 model文件夹建立一个 model文件( 如 /app/model/user.js )
代码如下(这里很关键,请详细阅读!):
'use strict';
module.exports = app => {
const { STRING, INTEGER } = app.Sequelize;
const User = app.model.define('user',
{
userid: { type: INTEGER, primaryKey: true, autoIncrement: true },
username: STRING(50),
sex: STRING(4),
userpass:STRING(32)
},
{
freezeTableName: true, // Model 对应的表名将与model名相同
timestamps: false,
}
);
return User;
};
离成功不远了!!!
'use strict';
const Controller = require('egg').Controller;
class UserController extends Controller {
async index() {
const _ctx = this.ctx
const user = await _ctx.model.User.findAll()
_ctx.body = user;
}
}
module.exports = UserController;
/app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/user', controller.user.index);
};
Congratulations!!!
大功告成!!!