ORM: Sequelize: 어떻게하면 몇몇 데이터를 제외하고 json을 리턴할 수 있나요?
조회수 1065회
안녕하세요.
sequelize 쿼리에 관한 질문입니다. 다대다 관계로 이루어진 테이블 3개를 쿼리합니다. 아래와 같은 쿼리를 하면:
const data = await product.findOne({
where: { product_id: id },
include: [
{
model: category
}
]
});
아래와 같은 json데이터를 return합니다:
"category": {
"product_id": 1,
"name": "Arc d'Triomphe",
"description": "This beautiful and iconic T-shirt will no doubt lead you to your own triumph.",
"price": "14.99",
"discounted_price": "0.00",
"image": "arc-d-triomphe.gif",
"image_2": "arc-d-triomphe-2.gif",
"thumbnail": "arc-d-triomphe-thumbnail.gif",
"display": 0,
"categories": [
{
"category_id": 1,
"name": "French",
"description": "The French have always had an eye for beauty. One look at the T-shirts below and you'll see that same appreciation has been applied abundantly to their postage stamps. Below are some of our most beautiful and colorful T-shirts, so browse away! And don't forget to go all the way to the bottom - you don't want to miss any of them!",
"department_id": 1,
"product_category": {
"product_id": 1,
"category_id": 1
}
}
]
}
위의 json 데이터를 아래와 같이 만들고자 합니다. 어떻게 쿼리해야 할까요?
"category": [
{
"category_id": 1,
"name": "French",
"department_id": 1
}
]
모델파일이 있어야 한다면 댓글 달아주실 수 있을까요?
감사합니다.
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
아래와 같이 쿼리합니다.
const query = await product.findOne({ where: { product_id: id }, include: { model: category, attributes: ['category_id', 'name', 'department_id'], through: { attributes: [] } }, attributes: [] });
그럼 아래와 같은 json 데이터가 나옵니다. 여기서 array bracket을 벗기는 가공을 따로 하면 됩니다.
"category": { "categories": [ { "category_id": 1, "name": "French", "department_id": 1 } ] }
키포인트는
through: { attributes: [] }
이었습니다.참조
-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력