first:搭建typescript语言的egg框架
$ npx egg-init --type=ts showcase(要新建的文件夹)
$ cd showcase
$ npm i
$ npm run dev
second:安装sequilize
$ npm i --save egg-sequelize
$ npm install --save mysql2
third:配置sequilize
config-plugin.js:
const plugin: EggPlugin = {
sequelize: {
enable: true,
package: 'egg-sequelize',
},
};
config-default.js:
config.sequelize = {
dialect: 'mysql',
host: 'xxxxxxxx',
port: 3306,
database: 'xxxxxx',
username: 'xxxxxxxx',
password: 'xxxxxx',
};
forth:使用
moodel-xxx.ts文件
module.exports = app => {
const Question = app.model.define('Question', {(该参数注释:表字段定义)}, {
freezeTableName: false,
tableName: 'interview_question', //表名
timestamps: true,
createdAt: 'create_time',
updatedAt: 'update_time',
getterMethods : { //获取器
}
});
return Question;
};
service-xxxx.js
public async getList()
{
const ctx = this.ctx;
try {
let question_list = await ctx.model.Question.findAll({
attributes : ['id','type', 'title'], //允许字段
limit: 30, //条数
order: [['id','desc']],// 排序
group: 'type' //分组
});
return question_list;
} catch (e) {
return e.toString();
}
}
controller-xxxxx.ts
public async getList() {
const { ctx } = this;
ctx.body = await ctx.service.question.getList();
}
暂时就到这里