Skip to content

Instantly share code, notes, and snippets.

@bharatsewani1993
Created December 31, 2021 13:06
Show Gist options
  • Save bharatsewani1993/ef68b057fd4c7ea58a3015943983412e to your computer and use it in GitHub Desktop.
Save bharatsewani1993/ef68b057fd4c7ea58a3015943983412e to your computer and use it in GitHub Desktop.
Sequlize Join
https://stackoverflow.com/questions/20460270/how-to-make-join-queries-using-sequelize-on-node-js
User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})
Post.find({ where: { ...}, include: [User]})
exports.getRelatedProducts = async (req, res) => {
try {
Model.Product.hasMany(Model.RelatedProducts, {foreignKey: 'product_id'})
Model.RelatedProducts.belongsTo(Model.Product, {foreignKey: 'id'})
const products = await Model.Product.findAll({
where: {id:{
[Sequelize.Op.ne]: req.query.productId
}},
include: [Model.RelatedProducts],
logging:console.log,
})
res.send({success:true,data:products})
} catch (error) {
res.send({success:false,data:[]})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment