Brackets 사용하기

louis220·2022년 6월 14일
0
  • register된 것 + (firstName이 Timber + lastName이 Saw)을 찾으려면...!
createQueryBuilder("user")
    .where("user.registered = :registered", { registered: true })
    .andWhere(new Brackets(qb => {
        qb.where("user.firstName = :firstName", { firstName: "Timber" })
          .orWhere("user.lastName = :lastName", { lastName: "Saw" })
    }))

다음의 쿼리와 같다

SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')
  • NotBrackets도 활용하면 좋을 듯 하다.
  • 배열안의 조건들을 만족하는 자료를 조회해야 할때는 조금 다르게 접근해야 하는데 단순하게 작성한 쿼리문을 쿼리빌더로 바꾸면 되는게 아니라 방법을 찾는데 꽤나 시간이 걸렸다
WHERE (status = ready and inspectionStatus = done) AND (status = waiting and inspectionStatus = consent)

=> 다음과 같아야 제대로 작동한다.

 filterStatus.forEach((val, index) => {
        if (filterStatus.indexOf(val) === 0) { => 첫번째 조건은 andWhere
          query.andWhere(
            new Brackets((qb) => {
              qb.where('receiving.status = :status', { status: val.status });
              if (val.inspectionStatus) {
                qb.andWhere('receiving.inspectionStatus = :inspectionStatus', {
                  inspectionStatus: val.inspectionStatus,
                });
              }
            })
          );
        } else {
          query.orWhere( => 2번째 조건부터는 orWhere
            new Brackets((qb) => {
              qb.where(`receiving.status = :status${index}`, { [`status${index}`]: val.status });
              if (val.inspectionStatus) {
                qb.andWhere(`receiving.inspectionStatus = :inspectionStatus${index}`, {
                  [`inspectionStatus${index}`]: val.inspectionStatus,
                });
              }
            })
          );
        }
      });
    }

참고:
https://typeorm.io/#/select-query-builder/adding-where-expression

profile
기록을 하자

0개의 댓글