【问题标题】:One-to-one relationship typeorm, save or update一对一关系typeorm,保存或更新
【发布时间】:2021-01-04 14:38:01
【问题描述】:

我正在尝试与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() 更新现有行,如果已经保存了培训师。

我做错了吗?

【问题讨论】:

    标签: nestjs typeorm one-to-one


    【解决方案1】:

    当您在实体上调用保存函数时,可能会发生两件事:

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

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

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

    export class TrainerDTO {
        id?: number;
    
        name: string;
    
        profile: ProfileDTO;
    }
    

    【讨论】:

      【解决方案2】:

      save 方法有两个功能,插入和更新。

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

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 2020-04-06
        • 2018-07-22
        • 2020-06-20
        • 2021-12-28
        • 2023-03-17
        • 1970-01-01
        • 2011-01-21
        相关资源
        最近更新 更多