一对一关系类型规范,保存或更新

时间:2020-09-17 16:34:00

标签: nestjs typeorm one-to-one

我正在尝试与nestjstypeormpostgres建立一对一的关系。

我有个人资料实体

  @OneToOne(() => Trainer, trainer => trainer.profile)
  @JoinColumn({ name: 'trainer_trainer_id' })
  trainer!: Trainer;

和培训师实体

  @OneToOne(() => Profile, profile => profile.trainer)
  profile!: Profile;

当用户提交申请成为Trainer时,我想在trainer表中用新行更新数据库,并在profile表中添加关联的ID。

因此,在培训师存储库中,我这样做:

  const trainer = CreateTrainerDto.toEntity(createTrainerDto);
    trainer.profile = profile;
    return await trainer.save();

这很好用,但是每次都会在trainer表中创建一个新行(并相应地更新profile表中的id)。但是我期望save()如果已经保存了培训师,则将更新现有行。

我做错了吗?

2 个答案:

答案 0 :(得分:1)

在实体上调用save函数时,可能会发生两种情况:

  • 如果提供的对象中没有id,TypeORM将在此表中插入新行。
  • 如果在对象中设置了id,TypeORM将更新与提供的实体id相对应的行。

由于您的DTO名为createTrainerDto,因此我假设您未提供实体的ID。因此,此代码将始终在表中插入新行。

创建DTO,以便id属性是可选的,这样您就可以使用DTO进行创建和更新。例如:

export class TrainerDTO {
    id?: number;

    name: string;

    profile: ProfileDTO;
}

答案 1 :(得分:1)

保存方法具有两种功能,即插入和更新。

如果提供的实体实例具有id值,则将执行更新,否则将插入。

因此,您可以执行以下操作:

const trainer = await this.trainerRepository.findOne(id) || this.trainerRepository.create(); // you can add the "or create" to have both create and update functionalities in one method
return await this.trainerRepository.save({...trainer, ...createTrainerDto, profile})