Joining tables in Sequelize
// import the Model(i.e Tables)
const Cart = require("../model/cart");
const Dish = require("../model/dish");
// define the association between the tables.
// doc link: https://sequelize.org/docs/v7/associations/basics/
Cart.hasMany(Dish, {
// equivalent of joining on Cart.dishId = Dish.id
foreignKey: "id",
sourceKey: "dishId",
});
// include the table you want to join.
// doc link: https://sequelize.org/docs/v7/querying/select-in-depth/#eager-loading-include
const cart = await Cart.findAll({
// include required attributes
// doc link: https://sequelize.org/docs/v7/querying/select-in-depth/#selecting-attributes
attributes: ["*", "Cart.*"],
include: [
{
model: Dish,
required: true,
},
],
where: { userId: req.params.userId },
});