首页 > 解决方案 > 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"

关系表不应该保留数据吗?

标签: typescriptsqlitegraphqltypeorm

解决方案


当您大量更改数据模型时,同步选项确实适用于开发,您应该在部署之前将其关闭。

同步 - 指示是否应在每次应用程序启动时自动创建数据库模式。请谨慎使用此选项,不要在生产中使用它 - 否则您可能会丢失生产数据。此选项在调试和开发期间很有用。作为替代方案,您可以使用 CLI 并运行 schema:sync 命令。


推荐阅读