简体   繁体   中英

How to generate entity files in NestJS and TypeORM

我来自 Java 背景,我们有工具可以直接从数据库生成 Java 实体( DTOsDAOsJPAs等)文件,现在正在处理NestJS项目并使用TypeORM ,我有我的表 ~ 30 表实现MySQL ,是否可以生成实体文件

What you are asking for is generally a Database First Approach to ORM, TypeORM does not support that natively AFAIK.

My best suggestion would be to implement a JSON to TS model and then map the required columns with TypeORM decorators. That will be your best bet.

For now, you can implement independent tables and then go along with other tables. I know its a long process. But modern ORMs are made to work with Entity first method.

You can use sequelize-typescript-generator library to create the entity and models automatically based on schema and connection.

From the description:

You can run this globally if you already install the package

For the usage of the command

-h, --host Database IP/hostname -p, --port Database port. Defaults: - MySQL/MariaDB: 3306 - Postgres: 5432 - MSSQL: 1433 -d, --database Database name -s, --schema Schema name (Postgres only). Default: - public -D, --dialect Dialect: - postgres - mysql - mariadb - sqlite - mssql -u, --username Database username -x, --password Database password -t, --tables Comma-separated names of tables to process -T, --skip-tables Comma-separated names of tables to skip -i, --indices Include index annotations in the generated models -o, --out-dir Output directory. Default: - output-models -C, --case Transform tables and fields names with one of the following cases: - underscore - camel - upper - lower - pascal - const You can also specify a different case for model and columns using the following format: <model case>:<column case> -S, --storage SQLite storage. Default: - memory -L, --lint-file ES Lint file path -l, --ssl Enable SSL -r, --protocol Protocol used: Default: - tcp -a, --associations-file Associations file path -g, --logs Enable Sequelize logs -n, --dialect-options Dialect native options passed as json string. -f, --dialect-options-file Dialect native options passed as json file path. -R, --no-strict Disable strict typescript class declaration.

Example of the command:

 stg \ -D mysql \ -h localhost \ -p 3306 \ -d myDatabase \ -u myUsername \ -x myPassword \ --indices \ --case camel \ --out-dir pathofthegeneratedfiletakeplace \ --clean \

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM