티스토리 뷰

관련 entity

  • couponPublish (ManyToOne)
  • coupon (OneToMany)
  • user (OneToMany)

 


사용한 문법 정리

- join 후 특정 컬럼만 가져오기

const newDate = new Date()
    newDate.setDate(newDate.getDate() + 7)
    const year = newDate.getFullYear()
    const month = newDate.getMonth() + 1
    const date = newDate.getDate()
    const formattedDate = `${year}-${month}-${date}`
      
await this.couponPublishRepository
    .createQueryBuilder('cp') // coupon_publish 테이블의 별칭
    .leftJoin('cp.user', 'user') // user 테이블 join 후 별칭(두번째 인자)을 'user'로 지정
    .leftJoin('cp.coupon', 'coupon') // coupon 테이블 join 후 별칭(두번째 인자)을 'coupon'으로 지정
    .select(['user.id', 'coupon.title']) // user의 id 컬럼, coupon의 title 컬럼만 가져옴
    .where('cp.endDate = :endDate', {
      endDate: formattedDate
    })
    .getRawMany() // getMany 대신 getRawMany 사용

getMany()는 엔티티를 가져오기 때문에 특정 컬럼만 가져오려고 하면 빈 배열을 반환한다 =>  getRawMany() 사용

// 1. getMany() 사용 결과
[]

// 2. getRawMany() 사용 결과
[ RowDataPacket { user_id: 3, coupon_title: '1일 체험 쿠폰' } ]

- RowDataPacket에 접근하려면 forEach 등의 반복문을 이용하면 됨

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함