Nestjs 一对一关系类型化、保存或更新

Nestjs 一对一关系类型化、保存或更新,nestjs,typeorm,one-to-one,Nestjs,Typeorm,One To One,我试图实现与nestjs、typeorm和postgres的一对一关系 我有一个个人资料实体 @OneToOne(() => Trainer, trainer => trainer.profile) @JoinColumn({ name: 'trainer_trainer_id' }) trainer!: Trainer; 和一个培训师实体 @OneToOne(() => Profile, profile => profile.trainer) pr

我试图实现与
nestjs
typeorm
postgres
的一对一关系

我有一个个人资料实体

  @OneToOne(() => Trainer, trainer => trainer.profile)
  @JoinColumn({ name: 'trainer_trainer_id' })
  trainer!: Trainer;
和一个培训师实体

  @OneToOne(() => Profile, profile => profile.trainer)
  profile!: Profile;
当用户提交成为培训师时,我想在
Trainer
表中用新行更新数据库,并在
profile
表中添加相关id

因此,在培训师存储库中,我会:

  const trainer = CreateTrainerDto.toEntity(createTrainerDto);
    trainer.profile = profile;
    return await trainer.save();
这很有效,但每次都会在
trainer
表中创建一个新行(并相应地更新
profile
表中的id)。但我希望
save()
在已保存培训师的情况下更新现有行


我做错了吗?

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

  • 如果提供的对象中没有id,TypeORM将在此表中插入新行
  • 如果在对象中设置了id,TypeORM将更新与提供的实体id对应的行
因为您的DTO被称为createTrainerDto,所以我假设您没有提供实体的id。因此,此代码将始终在表中插入新行

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

export class TrainerDTO {
    id?: number;

    name: string;

    profile: ProfileDTO;
}

save方法有两个功能,insert和update

如果提供的实体实例具有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})