raw query로 data update하기 (in typeORM)

손연주·2022년 5월 30일
0

프로젝트 id를 받아 stage가 4, 5인 raw data를 찾아서 stage를 17로 바꿔주는 작업을 진행했다. update 쿼리를 써보지 않아 헤매다가 구글링 끝에 Bulk update via raw query in TypeORM 문서를 찾았다. update 함수를 쓸 때엔 파라미터로 바꾸려고 하는 테이블을 받아야하고, where문에서는 In함수를 쓸 수 있다.

  async updateWorkStage(subtaskId: number) {
    const readyForPayStages = [4, 5];
	
    // 해당 stage와 subtaskId로 값의 변경이 있어야 하는 컬럼의 id값을 가져온다.
    const works = await this.worksRepository
      .createQueryBuilder('work')
      .select('work.id')
      .where('work.subtaskId = :subtaskId', { subtaskId })
      .andWhere('work.stage IN (:...readyForPayStages)', { readyForPayStages })
      .getRawMany();
	
    // id들을 배열에 담는다
    const ids = works.map((work) => work.work_id);

    // 배열에 담긴 id로 값을 찾아 stage를 변경해준다.
    await this.worksRepository
      .createQueryBuilder()
      .update(Work)
      .set({ stage: stages.TASK_STAGE_PAY_COMPLETED })
      .where({ id: In(ids) })
      .execute();
  }
profile
할 수 있다는 생각이 정말 나를 할 수 있게 만들어준다.

0개의 댓글