NestJS 에서 TypeORM 을 사용

 

게시물의 titlecontent 에 'keyword' 가 들어 있는 게시물 검색

    - Exception handeler 적용안하고 구현

 

board.controller.ts

// board.controller.ts
@Get('/keyword')
  @HttpCode(200)
  public async findKeyword(
    @Query('word') word: string,
  ): Promise<SearchKeywordBoardResponseDto[]> {
    return await this.boardService.findKeyword(word);
  }

 

!!! 어떻게 path 에 쿼리를 주고 받아 올것인가??? 이 부분에서 아주 많이 시간이 들었다.

1. query string 을 사용하는 방법을 잊어먹어서 이 부분에서 아주 많이 시간이 들었다.

    https://joey0203.tistory.com/192 <- 한번더 확인하자.

@Get('/keyword')

위와 같이 선언을 하여  주소가 http://localhost:3000/boards/keyword 이렇게 확장됨

 

@Queary('word') word: string,

 여기서 쿼리 값을 받아오기 위해 설정한 키가 'word' 가 되겠다.

 http://localhost:3000/boards/keyword?word=posting 를 해주면 posting 이라는 단어를 이용하여 검색하게된다.

 

 

board.service.ts

// board.service.ts
async findKeyword(keyword: string) {
    const searchResult = await this.boardRepository
      .createQueryBuilder('board')
      .where('board.title LIKE :key', { key: `%${keyword}%` })
      .orWhere('board.content like :key', { key: `%${keyword}%` })
      .execute();
    const result = [];
    searchResult.forEach((board) => {
      result.push(
        new SearchKeywordBoardResponseDto(
          board.board_id,
          board.board_title,
          board.board_content,
        ),
      );
    });
    return result;
  }

 

this.boadRepository  
.createQueryBuilder('board')

     - this.boadRepository : DB 에 있는 하나의 테이블을 호출 

     - createQueryBuilder('board') :  TypeORM 에서  제공하는 편리한 함수로써 SQL 쿼리문을 생성할 수 있도록 도와 준다. 이때 모                                                   든 열의 이름이 'board_id' 와 같은 형태로 자동으로 변환된다.

where( 'board.title LIKE :key', {key: `%${keyword}%`})

     - Like 함수를 이용 → LIKE, like LIke 다 된다. 대소문자 구별 필요없음

     - :key  내가 찾고싶은 값을 넣는 곳 

               → : key 사이에 빈공간 있으면 요청을 할때 에러발생

               → 'board.title LIKE :key' 을  `board.title LIKE  %${keyword}%` 로 써도 될거 같지만 안된다

orWhere('.......')

     - or 함수를 이용한 방식

getMany()

     - 여러개의 결과를 원할 때 사용

     - 하나의 결과를 원할 때는 getOne() 

 

SearchKeywordBoardResponseDto

     -  결과에 있는 id, title, content, created_at, updated_at, deleted_at 모든 값을 반환하지 않고 필요한 값만 보내기 위해 적용

참고자료

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

'프로그래밍 > SQL' 카테고리의 다른 글

[ ORM ] Sequlize : Model synchronization  (0) 2024.01.12
[ORM] Sequelize attributes  (0) 2024.01.08
Sequelize: ORM for MySQL  (0) 2023.12.30
MySQL- 가상의 테이블 View  (0) 2023.08.26
MySQL- 테이블 제약조건  (0) 2023.08.26
// 데이터베이스 
const sequelize = require('./config/database');

// 모든 모델을 한번에 동기화 하는 방법

// 1. 모든 데이터를 지우고 새로운 데이터베이스를 생성
sequelize.sync({ force: true });

// 2. 모델에 있는 기존의 데이터를 유지하면서 변경사항만 변경
sequelize.sync({ alter: true });

https://sequelize.org/docs/v6/core-concepts/model-querying-basics/#specifying-attributes-for-select-queries

 

Model Querying - Basics | Sequelize

Sequelize provides various methods to assist querying your database for data.

sequelize.org

 

원하는 콜롬보다 원하지 않는 콜롬이 더 많을 때 exclude 사용하면 편리

Model.findAll({
  attributes: { exclude: ['baz'] }
});

설치 라이브러리

npm i sequelize, mysql2

 

Operaters 

const {Op} = requier('sequelize');

 

사용방법 링크

https://sequelize.org/docs/v7/querying/operators/#basic-operators

 

Operators | Sequelize

Sequelize provides a large number of operators to help you build complex queries. They are available in the Op object, which can be imported from @sequelize/core.

sequelize.org

 

 

 

+ Recent posts