天天看點

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