SQL Association - through

brandon·2023년 6월 1일
0

MySQL

목록 보기
4/4

through는 many-to-many association에서 중요한 역할을 한다.

1. Retrieving data from junction table

Cart와 Product 모델이 many-to-many관계이고 CartProduct junction table에는 quantity data 가 있다고 해보자.

const Cart = sequelize.define('Cart', {
  // Cart model definition
});

const Product = sequelize.define('Product', {
  // Product model definition
});

const CartProduct = sequelize.define('CartProduct', {
  quantity: DataTypes.INTEGER,
});

Cart.belongsToMany(Product, { through: CartProduct });
Product.belongsToMany(Cart, { through: CartProduct });

Cart instance를 통하여 cart안에 있는 한 Product의 quantity를 알고 싶다면:

const cart = await Cart.findByPk(cartId);

// Retrieve the quantity of a specific product in the cart
const quantity = await cart.getProducts({
  where: { id: productId },
  through: { attributes: ['quantity'] },
  plain: true //javascript object로 return한다.
});

console.log(quantity); // quantity object를 log한다.
profile
everything happens for a reason

0개의 댓글