具有ManyToMany关系的Typeorm在更新时删除数据

问题描述 投票:0回答:1

我与数据透视表有多对多关系,当我尝试附加新值(包括旧值)时,Typeorm 会删除旧值。

export class VHost {
//....
}

export class Migration {
  @Column({ name: 'migration_id', type: 'uuid' })
  migrationId: string;

@ManyToMany(() => VHost, { cascade: true, eager: true })
  @JoinTable({
    name: 'instance_failed_vhost',
    joinColumn: { name: 'migration_id', referencedColumnName: 'migrationId' },
    inverseJoinColumn: {
      name: 'dest_vhost_id',
      referencedColumnName: 'vHostId',
    },
  })
  failedDestVhosts: VHost[];
}

保存工作正常,就像 fr 第一次工作正常,更新:假设 failedDestVhosts=[VHost1, VHost2],同时更新为 failedDestVhosts=[VHost1, VHost2,VHost3,VHost4]

它插入 4,然后从数据透视表中删除 VHost1、VHost2

我希望更新后保留 4 个虚拟主机

typeorm nestjs-typeorm
1个回答
0
投票

这就是 TypeORM 中多对多关系的工作方式 如果您想保留原始实体,您需要将其与实体一起加载。

const migration = await migrationRepository.findOne({
  where: { migrationId: 'someId' },
  relations: {
    failedDestVhosts: true,
  },
});

migration.failedDestVhosts = [...migration.failedDestVhosts, newVHost];
// now you can save it
© www.soinside.com 2019 - 2024. All rights reserved.