eggjs中,自動(dòng)從數(shù)據(jù)庫直接生成model.
使用sequelize-auto可以自動(dòng)生成models
https://www.npmjs.com/package/sequelize-auto
直接上命令就可以搞定了
# 安裝必要的庫
npm install -g sequelize-auto
# MySQL/MariaDB 數(shù)據(jù)庫安裝對(duì)應(yīng)的庫,其他數(shù)據(jù)庫請(qǐng)看文檔
npm install -g mysql
# 從命令行生成models
sequelize-auto -o './database/models' -h localhost -d databasename -u username -x password -p 3306
將sequelize-auto與eggjs結(jié)合
安裝必要的庫
npm install -D sequelize-auto
npm install -D mysql
注意:安裝參數(shù)為-D,是在開發(fā)模式使用.
寫運(yùn)行文件 ./database/autoModels.js
'use strict';
const SequelizeAuto = require('sequelize-auto');
const devConfig = require('../config/config.dev.js')();
const config = require('../config/config.default.js')({ name: '' });
const db = {
database: devConfig.sequelize.database || config.sequelize.database,
host: devConfig.sequelize.host || config.sequelize.host,
port: devConfig.sequelize.port || config.sequelize.port,
username: devConfig.sequelize.username || config.sequelize.username,
password: devConfig.sequelize.password || config.sequelize.password,
dialect: devConfig.sequelize.dialect || config.sequelize.dialect,
};
const auto = new SequelizeAuto(db.database, db.username, db.password, {
host: db.host,
dialect: db.dialect,
directory: './database/models/', // prevents the program from writing to disk
port: db.port,
additional: {
timestamps: false,
},
// tables: [] // 指定表格
// ...
});
auto.run(function(err) {
if (err) throw err;
console.log(auto.tables); // table list
console.log(auto.foreignKeys); // foreign key list
});
在package.json中添加啟動(dòng)執(zhí)行項(xiàng)目
# 加入 "scripts" 段中.
"db:autoModels":"node ./database/autoModels"
執(zhí)行命令,自動(dòng)生成models
npm run db:autoModels
生成Models后可以根據(jù)里面的內(nèi)容,稍作修改作為eggjs的model使用.