티스토리 뷰
라이브러리, 프레임워크/TypeORM
[TypeORM + NestJS] select 시 oneToMany 관계 count 해서 함께 조회하기 (loadRelationCountAndMap)
dv_jamie 2023. 1. 5. 21:04loadRelationCountAndMap 이용
await this.testRepository
.createQueryBuilder('user')
.select([
'user.id',
'user.name'
])
.loadRelationCountAndMap('user.followerCount', 'user.follwers')
.getMany()
/**
* Counts number of entities of entity's relation and maps the value into some entity's property.
* Optionally, you can add condition and parameters used in condition.
*/
loadRelationCountAndMap(mapToProperty: string, relationName: string, aliasName?: string, queryBuilderFactory?: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>): this;
// 예시
const found = await this.usersRepository.createQueryBuilder('user')
.loadRelationCountAndMap(
'user.unreadEventCount',
'user.events',
'event',
(qb) => qb.where('event.readAt IS NULL')
)
.getMany();
- 첫번째 인자로 내가 지정할 property 이름 (mapToProperty: string)
- 두번째 인자로 entity에서 입력했던 관계테이블의 이름 (relationName: string)
결과
[
{
"id": 1,
"name": "유저1",
"followerCount": 13
},
{
"id": 2,
"name": "유저2",
"followerCount": 33
},
{
"id": 3,
"name": "유저3",
"followerCount": 14
}
]
단점
위의 결과로 나온 followerCount를 기준으로 정렬을 하고 싶어 폭풍검색을 해봤지만 방법이 없었다
subQuery는 따로 매핑을 시켜줘야 해서 loadRelationCountAndMap의 결과를 그대로 사용하고 싶었는데,
subQuery를 사용할 수 밖에 없다고 한다
- loadRelationCountAndMap는 엔티티에 map은 되지만 해당 count를 기준으로 정렬은 할 수 없다
- count로 정렬을 하려면 subQuery를 활용해야 하지만, subQuery는 정렬은 되는 대신 map이 안된다 (;;)
query
.loadRelationCountAndMap('user.itemCount', 'user.items', 'itemCount') // mapped, but can't be sorted.
.addSelect((qb) => {
return qb.select('COUNT(item.id)', 'count').from(ItemEntity, 'item'); // can't be mapped, but can be sorted. ( getMany )
}, 'count')
.orderBy('count', 'DESC');
참고사이트
'라이브러리, 프레임워크 > TypeORM' 카테고리의 다른 글
[TypeORM + NestJS] 일기 생성 API - oneToMany, manyToMany save 로직 기록 (0) | 2023.01.01 |
---|---|
[TypeORM] limit와 offset / take와 skip 차이 (0) | 2022.08.08 |
[TypeORM + NestJS] optional 하게 조건절 사용하기 (0) | 2022.08.03 |
[TypeORM + NestJS] Unknown column 'distinctAlias.User_id' in 'field list'" 에러 (0) | 2022.07.21 |
[TypeORM] 페이징 처리 문법 (0) | 2022.07.15 |
댓글