sequelize-auto 同步生成数据模型

日期: 2019-03-22         浏览量: 3140

在使用sequelize这种orm框架时,我们需要先建立数据模型,在同步生成表结构,而有时我们需要重构一个项目时,在表结构已将建立好的情况下,在去建立数据模型,这是一件繁琐的事情。

sequelize-auto 自动同步表数据接口生成数据模型。


1. 安装

    npm install -g sequelize-auto


    使用的mysql

    npm install -g mysql


2. 命令-同步建立模型

    

    sequelize-auto -o "./models" -d sequelize_auto_test -h localhost -u my_username -p 5432 -x my_password -e postgres


    参数说明:

    

    -h, --host        IP/Hostname for the database.   [required]
    -d, --database    Database name.                  [required]
    -u, --user        Username for database.
    -x, --pass        Password for database.
    -p, --port        Port number for database.
    -c, --config      JSON file for Sequelize's constructor "options" flag object as defined here: https://sequelize.readthedocs.org/en/latest/api/sequelize/
    -o, --output      What directory to place the models.
    -e, --dialect     The dialect/engine that you're using: postgres, mysql, sqlite
    -a, --additional  Path to a json file containing model definitions (for all tables) which are to be defined within a model's configuration parameter. For more info: https://sequelize.readthedocs.org/en/latest/docs/models-definition/#configuration
    -t, --tables      Comma-separated names of tables to import
    -T, --skip-tables Comma-separated names of tables to skip
    -C, --camel       Use camel case to name models and fields
    -n, --no-write    Prevent writing the models to disk.
    -s, --schema      Database schema from which to retrieve tables
    -z, --typescript  Output models as typescript with a definitions file.


3. 脚本-同步建立数据模型

    

    

const SequelizeAuto = require('sequelize-auto');
const config = require('../biz/configs');

let auto = new SequelizeAuto(config.database, config.user, config.password, {
            host: config.host,
            dialect: 'mysql',
            directory: `./biz/lib/db/models/`, // prevents the program from writing to disk
            port: config.port,
            additional: {
                timestamps: false
            },
        })
        auto.run(function (err) {
            if (err) throw err;
            console.log(auto.tables); // table list
            console.log(auto.foreignKeys); // foreign key list
        });