through는 many-to-many association에서 중요한 역할을 한다.
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한다.