typescript - Typeorm synchronize:true在实体更改时清空manyToMany关系表
问题描述
我是 typeorm 的新手,但我看到一个非常奇怪的synchronize: true
功能问题,设置在我的ormconfig.js
. 当我修改具有多对多关系的实体时,在进行实体更改之前连接表中的任何数据都会被删除。
这是我的Project
实体
@ObjectType()
@Entity("project")
export class Project extends BaseEntity {
@Field(() => Int)
@PrimaryColumn()
id: number;
@Field()
@Column("text")
name: string;
@Field({ nullable: true })
@Column("text", { nullable: true })
cluster?: string;
//project_groups
@ManyToMany((type) => Group, (group) => group.projects, { lazy: true })
@Field((type) => [Group], { nullable: true })
@JoinTable()
groups?: Group[];
}
这是我的Group
实体
@ObjectType()
@Entity("group")
export class Group extends BaseEntity {
@Field(() => String)
@PrimaryColumn()
id: string;
@Field()
@Column("text")
name: string;
@Field({ nullable: true })
@Column("text")
type: string;
@Field({ nullable: true })
@Column("text", { nullable: true })
currency: string;
@Field((type) => [Project])
@ManyToMany((type) => Project, (project) => project.groups, { lazy: true })
projects: Project[];
//group_modifiers
@ManyToMany((type) => Modifier, (modifier) => modifier.group, { lazy: true })
@Field((type) => [Modifier])
@JoinTable()
modifiers: Modifier[];
}
如果我向 Group 或 Project 添加一个新字段,迁移将自动运行,并且以下查询
query: CREATE TABLE "temporary_project" ("id" integer PRIMARY KEY NOT NULL, "name" text NOT NULL, "cluster" text, "asdfa" text)
query: INSERT INTO "temporary_project"("id", "name", "cluster") SELECT "id", "name", "cluster" FROM "project"
query: DROP TABLE "project"
query: ALTER TABLE "temporary_project" RENAME TO "project"
关系表不应该保留数据吗?
解决方案
当您大量更改数据模型时,同步选项确实适用于开发,您应该在部署之前将其关闭。
同步 - 指示是否应在每次应用程序启动时自动创建数据库模式。请谨慎使用此选项,不要在生产中使用它 - 否则您可能会丢失生产数据。此选项在调试和开发期间很有用。作为替代方案,您可以使用 CLI 并运行 schema:sync 命令。
推荐阅读
- sql - 如何将 X 秒添加到 SQL 中的多行?
- android - React Native Maps:标记图像不显示在 react-native-maps 中使用自定义标记
- c++ - 使用 splashkit 依次显示多个 C++ 图像
- c# - .NET C#:HttpClient 和 TaskCanceledException 异常
- python - 如何在 Django 中访问 html?
- php - PHP:无法解码 base64 编码的 JPEG
- java - Tomcat 9 / JNDI 数据源 - 无法为连接 URL 'null' 创建类 '' 的 JDBC 驱动程序
- php - 如何从 Slim 微框架中的 JSON 文件中读取数据?
- apache-nifi - Nifi validaterecord 和 convertrecord 使用 avroschemaregistry 验证和转换 json 记录
- c# - 将 XML 数据转换为 C# 类