혼자 고민해보기_ 개발/TIL (Today I Learned)

20230720(금)_ 백오피스 프로젝트

nuri-story 2023. 7. 22. 12:07

 금일 달성 항목

1) 상세페이지 리뷰 정보 가져오기, 구매하기 화면 구현


문제 해결 과정 1 - 상세페이지 리뷰 가져오기

[문제]

상세페이지에서 리뷰를 가져오려고 했는데 ERD를 보면 음식점 > 리뷰 > 고객까지 타고들어가서 가져와야하는 상황이라 include로 연결하면 되는지 잘 모르는 상황이었습니다.

[시도 및 해결]

튜터님과 팀원들에게 상의해보니 방법은 2가지가 있었습니다.

1. 고객을 따로 레포지토리에서 가져옵니다.

2. 음식점에 연결하여 고객을 불러옵니다.

라우터에서 코드를 짜려면 2번이 좀더 수월하고 코드도 간결하게 짜질 것 같아서 2번으로 시도했습니다.

 

render.router.js

// 서브 페이지 진입,
router.get('/sub-page/:restaurant_id', async (req, res) => {
  const restaurant_id = req.params.restaurant_id;
  const restaurantResult = await restaurantsRepository.getRestaurant({ restaurant_id });

  const data = restaurantResult[0].dataValues;
  let restaurant = data;

  let menus = data.Menus.map((menu) => menu.dataValues);
  let reviews = data.Reviews.map((review) => review.dataValues);

  res.render('sub-page', { restaurant, menus, reviews });
});

 

레스토랑 레포지토리

  // 음식점 조회
  getRestaurant = async ({ restaurant_id }) => {
    return await Restaurant.findAll({
      where: { restaurant_id },
      attributes: [
        'restaurant_id',
        'Owner_id',
        'name',
        'address',
        'phone_num',
        'biz_hours',
        'category',
        'createdAt',
        'updatedAt',
      ],
      include: [
        {
          model: Menu,
        },
        {
          model: Review,
          include: [
            {
              model: Client,
            },
          ],
        },
      ],
      order: [['createdAt', 'DESC']],
    });
  };

include를 두번 연결하는 것도 방법이었습니다.

 

[알게된 점]

이 방법이 가장 최선의 방법인지는 모르겠습니다... 좀 더 공부해야할 것 같습니다.