반응형
showMeTheOrder = async (userId) => {
try {
const showOrder = await this.orderModel.findAll({
where: { userId },
attributes: [
"id", "receiverName", "receiverAddress", "receiverPhone", "total_Price"
],
include: [
{
model: this.cartModel,
attributes: ["quanitity", "isDone", "updatedAt",],
include: [
{
model: this.goodsModel,
attributes: ["name", "price", "image",]
}
]
}
]
})
return showOrder
} catch (error) {
throw error
}
}
Sequelize를 이용해서 2번이상 join을 할일이 별로 없었지만 이번 프로젝트를 하면서 처음 사용하게 되었다.
주문에 대한 정보를 보기위해서 처음 계획부터 order에서 join해서 가져오자는 계획을 세웠지만 실제로 해보는건 처음이어서
구글링을 해서 알아보고 했다.
Orders -> Carts -> Goods 순서로 include한 테이블안에서 한번더 include를 했다.
만약 Orders에 Goods관련 컬럼이 있었으면 다른 방식으로 하게된다. -> ERD에 더 많은 시간을 사용하자....
createOrder = async (
cartId, userId, receiverName, receiverAddress, receiverPhone, total_Price
) => {
const t = await sequelize.transaction()
try {
const findCart = await this.cartModel.findAll({
where: { id: cartId },
transaction: t
})
console.log('111', findCart)
if (!findCart.length) {
throw new Error('없는 카트입니다.')
}
if (findCart[0].isDone !== 1) {
throw new Error('이미 주문된 카트입니다.')
}
const createOrder = await this.orderModel.create({
userId,
receiverName,
receiverAddress,
receiverPhone,
total_Price,
}, { transaction: t })
await this.cartModel.update(
{ isDone: 0 },
{
where: { id: cartId },
transaction: t
}
);
await this.cartModel.update(
{ orderId: createOrder.id },
{
where: { id: cartId },
transaction: t
}
);
await t.commit()
return createOrder
} catch (error) {
await t.rollback()
throw error
}
}
시퀄라이즈 transaction도 처음 사용해봤다. 동시에 처리되어야 하는 일을 하나의 묶음으로 만들어서 하나라도 안되면 동작이 되지 않게 해주는 기능이다.
transaction을 선언하고 들어가야 하는 부분에 transaction: t를 넣어주고 마지막에 await t.commit()을 해줘야 한다. 이거 빼먹어서 오류가 많이 났다....
transaction에 대해서는 구글링해서 사용법만 익히고 넣은것이어서 프로젝트 끝나고 좀 더 살펴봐야겠다.
반응형