【问题标题】:TypeOrm transaction with method in other serviceTypeOrm 事务与其他服务中的方法
【发布时间】:2021-08-17 18:12:38
【问题描述】:

我将 typeorm 与 nestjs 一起使用。 但我不知道如何使用方法来使用事务

例如,

async createTrack(track) {
try {

  const createdTrack = await this.createTrack(track);

  //this.boardService.createBoard will work by transaction.
  const board = await this.boardService.createBoard({
      ...track.board
  });

  return board;
} catch (e) {
  throw e;
}

我想使用boardSerivce的方法进行交易。

怎么办?


我解决了。

试试看。 TypeORM transaction with query builder

使用https://github.com/odavid/typeorm-transactional-cls-hooked

【问题讨论】:

    标签: transactions nestjs typeorm


    【解决方案1】:

    您检查过文档吗? https://docs.nestjs.com/techniques/database#transactions

    从上面的文档中复制

    const queryRunner = this.connection.createQueryRunner();
    
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        await queryRunner.manager.save(users[0]);
        await queryRunner.manager.save(users[1]);
    
        await queryRunner.commitTransaction();
      } catch (err) {
        // since we have errors lets rollback the changes we made
        await queryRunner.rollbackTransaction();
      } finally {
        // you need to release a queryRunner which was manually instantiated
        await queryRunner.release();
      }
    

    【讨论】:

    • 是的,我查过了。但是如何使用 queryRunner 的方法?因为我想在其他服务中回收我的自定义方法。我不想重写相同功能的相同代码
    • 谢谢。我解决它。 stackoverflow.com/questions/68697866/…
    • 很好,您可以更新您的原始问题以反映您真正想要什么以及您发现了什么,以便其他人可以从中受益
    猜你喜欢
    • 2020-02-29
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2011-07-02
    • 2022-12-23
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多