NestJS 에서 TypeORM 을 사용
게시물의 title 과 content 에 '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
'DataBase > SQL' 카테고리의 다른 글
[ sql ] [ TypeORM ] Entity 의 constructor (0) | 2024.07.04 |
---|---|
[sql][typeORM] N:M 관계에서 원하는 데이터찾기 (0) | 2024.06.22 |
[ ORM ] Sequlize : Model synchronization (0) | 2024.01.12 |
[ORM] Sequelize attributes (0) | 2024.01.08 |
Sequelize: ORM for MySQL (0) | 2023.12.30 |