티스토리 뷰

loadRelationCountAndMap 이용

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');

 


참고사이트

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함