티스토리 뷰

키워드1

문제점

Sequelize 쿼리문으로 데이터 조회 요청시 join을 하게 되면 해당 데이터가 객체 형태로 합쳐지게 되는데 이를 원래 데이터와 같은 형태로 합치고 싶었다.

시도해본 것들

include를 이용한 다양한 예시들을 따라해 봤다

해결

아래와 같이 코드를 짜서 해결했다

  findReviewByOwnerId = async (ownerId) => {
    const review = await this.reviewModel.findAll({
      raw: true,
      attributes: {
        include: ['Service.customerId', 'Service.customer.nickname'],
      },
      include: [
        {
          model: this.serviceModel,
          attributes: [],
          where: { ownerId },
          include: [
            {
              model: this.userModel,
              as: 'customer',
              attributes: [],
            },
          ],
        },
      ],
    });
    return review;
  };

알게 된 점

attributes 안에 include를 써주면 원하는대로 깔끔하게 데이터가 얻어진다. 이 때 include하는 model들의 attributes는 빈 배열을 주어 아예 얻어지지 않게 하는게 중요하다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함