1.npm 安装必要的库(-D等参数可以自定义,按照自己需求)
npm install egg-sequelize-auto
npm install mysql2
2.使用命令生成model
egg-sequelize-auto -o "models" -d databasename -h localhost -u username -p port -x password -e mysql
//model改为model存放的地址
//localhost改为主机地址
//databasename改为数据库名
//username改为用户名
//password改为用户名的密码
//port改为端口号
//mysql改为数据库类型
//以下为例子
//egg-sequelize-auto -o "./app/model" -d ms-test-learning-pro02 -h 120.78.172.212 -u root -p 3306 -x Mashang10.01 -e mysql
自动生成的model效果如下(大致上和你需求差不多,需要稍作修改)
1.自动递增不会加上去,需要自己加
2.若自定义table名字则tableName那一块需要删掉
3.若有定义created_at等需要自己添加或删除
3.导出的model最好与表名类似
自动生成的例图:
/* indent size: 2 */
module.exports = app => {
const DataTypes = app.Sequelize;
const Model = app.model.define('ms_dict', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true
},
type: {
type: DataTypes.STRING(255),
allowNull: true
},
value: {
type: DataTypes.STRING(255),
allowNull: true
},
label: {
type: DataTypes.STRING(255),
allowNull: true
}
}, {
tableName: 'ms_dict'
});
Model.associate = function() {
}
return Model;
};
改完之后例图:
/* indent size: 2 */
'use strict';
module.exports = app => {
const DataTypes = app.Sequelize;
const MsDict = app.model.define('ms_dict', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
type: {
type: DataTypes.STRING(255),
allowNull: true,
},
value: {
type: DataTypes.STRING(255),
allowNull: true,
},
label: {
type: DataTypes.STRING(255),
allowNull: true,
},
}, {
updatedAt: false,
createdAt: false,
});
MsDict.associate = function() {
};
return MsDict;
};