安装sequelize-typescript插件
cnpm install --save-dev @types/node @types/validator
cnpm install sequelize reflect-metadata sequelize-typescript
在midway项目src目录下创建model文件夹,用来存储模型对象(文件夹名称可以自定义),然后在model文件夹下创建user.ts文件
import {Length, PrimaryKey,Default,HasMany,AutoIncrement,Table, Column, Model,CreatedAt,UpdatedAt,DeletedAt } from 'sequelize-typescript'
@Table({
timestamps: true, // 自动维护时间
tableName:"user", // 数据库表名称
freezeTableName: true, // 禁止修改表名,如果不写会把表名自动复数化,users
paranoid: true, // 软删除
})
export class User extends Model<User> {
@AutoIncrement // 自增
@PrimaryKey // 主键
@Column
id: number;
@Length({max:50})
@Column
name: string;
@Column({
defaultValue:"",
comment:"用户手机号"
})
phone:string;
@Column({
defaultValue:"",
comment:"用户邮箱"
})
email:string;
@Default(new Date())
@CreatedAt
@Column
createDate: Date;
@Default(new Date())
@UpdatedAt
@Column
updateDate: Date;
@DeletedAt
deleteDate: Date;
}
在model文件夹下创建index.ts文件
// model多了在这里配置,用于数据库同步使用
import {User} from './User';
export default [
User
]
编辑config目录下config.*.ts(环境配置参数),配置sequelize数据库链接参数
export const sequelize = {
dialect: 'mysql',
host: '',
port: 3306,
database: '',
username: '',
password: '',
timezone: '+08:00', // 时区
};
编辑configuration.ts 如果没有自己在src目录下创建一个
import { Sequelize } from 'sequelize-typescript';
import { App, Configuration,Config } from '@midwayjs/decorator';
import { ILifeCycle,IMidwayContainer } from '@midwayjs/core';
import { Application } from 'egg';
import dbArray from './model/index'
@Configuration({
imports:[
...
],
importConfigs: [join(__dirname, './config')],
conflictCheck: true,
})
export class ContainerLifeCycle implements ILifeCycle {
@App()
app: Application;
@Config('sequelize')
seqConfig
async onReady(container: IMidwayContainer) {
const sequelize = new Sequelize(this.seqConfig)
sequelize.addModels(dbArray)
if (json_params.asyncdb) {
await sequelize.sync({
alter: true
});
process.exit(1);
}
}
}
在package.json中添加一行指令
"scripts": {
···
"asyncdb": "cross-env ets && cross-env NODE_ENV=local midway-bin dev --ts --asyncdb",
···
},
至此 ---
命令行以下命令即可同步数据库
npm run asyncdb