one to one
Product.belongsTo(User, { constraints: true, onDelete: "CASCADE" });
cascade defines how the
products are behave on user delete
User.hasMany(Product); one to many
User.hasOne(Cart); one to one
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem }); many to many
Product.belongsToMany(Cart, { through: CartItem });
Belongs To Many wants to
parse the middle connection manually.
like person----->orders<-----products
Advanced
middleware controller function
user has one cart and cart
has many products
exports.getProductCart = (req, res, next) => {
req.user
.getCart() // one to one mapping
.then((cart) => {
cart
.getProducts() //one to many mapping so
->s
.then((products) => {
console.log(products);
res.render("shop/cart", {
pageTitle: "Shop Cart",
active: "cart",
products: products,
});
});
})
.catch((err) => {
console.log(err);
});
};
Eager
Loading
Eager
loading is the process whereby a query for one type of entity also loads related
entities as part of the query.
(fetch
another table data along with the requested table)
(order table->
comes with products data)
exports.getOrders = (req, res, next) => {
req.user
.getOrders({ include: ["products"] })
.then((orders) => {
res.render("shop/orders", {
pageTitle: "Orders Page",
active: "orders",
orders: orders,
});
})
.catch((err) => {
console.log(err);
});
};

0 Comments