Database/mysql

[typeORM] QueryBuilder/relations : 원하는 속성 select 하기

아2 2023. 8. 24. 02:39

[✅ 원하는 내용 셀렉트 하기]

*innerJoin 한 테이블의 속성들도 select를 통해서 원하는 정보만 반환할 수 있음. 

(Join Table 결과를 모두 반환하고 싶다면 InnerJoinAndSelect이나 leftJoinAndSelect 사용하면 됨.)

    const user = await this.usersRepository
      .createQueryBuilder('user')
      .innerJoin('user.likes', 'likes')
      .innerJoin('likes.product', 'product')
      .select([
        'user.email',
        'user.name',
        'user.phone_number',
        'user.address',
        'user.point',
        'likes.id',
        'likes.created_at',
        'product.product_name',
        'product.product_price',
        'product.product_thumbnail',
      ])
      .where('user.id = :id', { id: user_id })
      .getOne();

 

 

[✅ 개수 카운트해서 객체로 반환하기]

-loadRelationCountAndMap

const user = await this.usersEntity
  .loadRelationCountAndMap('user.like_count', 'user.likes') // 이 부분
  .getOne();

 

 

[단순히 해당 엔티티 속성을 셀렉하지 않고, 연결한 엔티티의 속성만 셀렉하면 된다면 아래처럼 해도 된다.]

=> 하지만 이것도 @JoinColumn 설정하지 않으면 불안정함.

 const reservationData = await this.reservationRepository.find({
      where: { User_id: user_id },
      relations: ['performance'],
      select: {
      	id: true,
        name: true
      },
    });
 const reservationData = await this.reservationRepository.find({
      where: { User_id: user_id },
      relations: ['performance'],
      select: {
        performance: { perf_name: true, perf_price: true },
      },
    });