如何使用 typeorm 向现有实体添加新列

How to add a new column to an existing entity with typeorm

我正在开始研究 typeorm,但我对如果我将一个新列添加到一个已经与数据保持一致的现有实体会发生什么感到困惑。我使用 SQlite。

我在文档中看到,在 "Migrations" 部分,如果我想添加一个新列,似乎有一个必须完成的过程。

但是当我看到 this issue in typeorm's github 时,我明白如果我只是将注释 属性 的新“@Column”添加到实体 class 就足够了,typeorm 会创建应用程序启动时自动列。

我真的希望 typeorm 能够自动处理架构更改。

有人可以帮忙吗?

TypeOrm 能够更改架构,但不会 运行 在服务器启动时自动迁移(这不是我们想要的行为)。如果您希望在应用程序启动时执行迁移,您需要执行以下步骤:

  1. 创建迁移文件:

更改实体(如添加新列)后,您需要生成一个迁移文件:

typeorm migration:generate -c 'connectionName'

该迁移文件随后会创建到您 ormconfig.json 中配置的文件夹中。

  1. 运行 迁移

在启动服务器之前,您需要创建数据库连接和 运行 迁移。所以你的主文件应该看起来像

import { Connection, getConnectionManager } from 'typeorm';

const connectionManager = getConnectionManager();
const connection = connectionManager.get(connectionName);
await connection.runMigrations();

// start your server
startServer();

出于开发目的,您还可以使用模式同步,在这种情况下,typeorm 会将您的数据库与您的实体同步:

npx typeorm schema:sync -c 'connectionName'

我不太精通 NestJS,但我们也可以 运行 迁移取决于字段的 typeORM 配置文件设置 - migrationsRun:true 该字段的文档描述为:Field indicates if migrations should be auto run on every application launch. Alternative to it, you can use CLI and run migrations:run command. 所以它的额外方法 运行 它没有:

const connectionManager = getConnectionManager();
const connection = connectionManager.get(connectionName);
await connection.runMigrations();