天天看点

Sequelize自动对数据库表的映射(自动在koa项目里生成model)

连接好表后,需要使用Sequelize进行对数据库表的映射,很多博客会教你如何写,其实它是可以自动生成的:下图是数据库的表,我们需要给他们建立映射。

Sequelize自动对数据库表的映射(自动在koa项目里生成model)

​ 需要全局安装sequelize-auto:sequelize-auto

使sequelize-auto命令操作数据库(MySQL):npm install -g tedious

根据sequelize-auto自动生成model且生成指定的表对应的js:(以studio表为例)

sequelize-auto -h localhost -d ttms -u root -x 123456 -p 3306 -t studio

其中,

-h是你的数据库IP地址

-d是数据库库名

-x是数据库密码

-p 是数据库端口号

-t是需要映射的表名

但是,需要注意的是由于是自动生成的,有的地方还有问题,(例如自增长在映射里老是不会自动生成)使用时需要敏感一些,如有问题就手动写一些语句辅助

Sequelize自动对数据库表的映射(自动在koa项目里生成model)

其他:命令中相关参数介绍:

-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

如果无法解决,请重新尝试篇文章里的方法: Sequelize2020指引

koa