What I Learned/SpartaCodingClub
[내일배움캠프] 2023-01-06 TIL
Interrobang
2023. 1. 6. 18:09
키워드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는 빈 배열을 주어 아예 얻어지지 않게 하는게 중요하다.