I have three tables User , subproducts and Likes
db.SubProduct.hasMany(db.Like, { foreignKey: "ProductId", as: "likes" });
db.Users.hasMany(db.Like, { foreignKey: "userId", as: "likedProducts" });
db.Like.belongsTo(db.Users,{foreignKey: "userId", as: "likedProducts"})
db.Like.belongsTo(db.SubProduct, { foreignKey: "ProductId", as: "likes" });
this is my foreign keys to link tables to each other
I am calling this function to fetch the subproducts with likeCount field in it
const Products = await db.SubProduct.findAll({
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("likes.id")), "LikeCount"]]
},
include: [
{
model: db.Like, as: "likes", attributes: []
}
],
group: ['SubProduct.id']
});
the function is working fine it is giving me the product data with likecount in it.
but I want get one field along with a field isLiked which will true or false .
if the user id which is provided in the token has liked that product then the isLiked field will be true otherwise it will be false
here is the reference question from where I got this function to get likecount now I want to learn about how to get isLiked field
How can users like and unlike each others post using sequelize postgres nodejs?