[TypeORM] SQL문 LIKE를 createQueryBuilder를 통해 사용하기

@Query를 활용하여 ?word={검색 단어}의 형식으로 검색 API를 구성하였다.

// story.service.ts

async findByWord(word: string) {
    return await this.repository.find({
      where: [{ title: word }],
      select: ['id'],
    });

위의 코드와 같이 구성하면, 해당 검색 단어와 일치하는 결과'만' 검색할 수 있다.

예를 들어 스토리의 제목이 "빨간 의자를 포함된 스토리" 이면 "빨간 의자" 혹은 "스토리"의 단어로는 해당 스토리가 검색되지 않는다.

검색 단어를 포함하고 있는 검색 결과를 얻기 위해서는 SQL문의 LIKE를 사용하면 된다. NestJS와 TypeORM을 사용하고 있기 때문에 TypeORM의 createQueryBuilder( )를 사용하여 다음과 같이 구성하였다.

// story.service.ts

async findByWord(word: string) {
  return await this.repository
        .createQueryBuilder('product')
        .where('product.name like :name', { name: `%${word}%` })
        .select('product.id')
        .getMany();
    }

.where( )안에 like를 포함시키고, 변수에 `%를 추가하는 방식으로 createQueryBuilder에서 SQL문의 LIKE를 추가하였다.

 

참고) https://stackoverflow.com/questions/47814537/how-to-perform-a-like-query-typeorm

 

How to perform a like query Typeorm

Hello guys I'm trying to find all the results that have a in them. I have tried a couple of ways but the problem is nothing works. It just returns an empty array var data = await getRepositor...

stackoverflow.com