I have categories table that has many products and that products table has many images
I am able to get them separately but i want them together in one go
const categoriesList = await Categories.findAll({
include:['myProducts']
})
and my relations are as follows
db.Products.hasMany(db.ProductImages,{as:"productImages",foreignKey: 'productId' })
db.Categories.hasMany(db.Products,{as:"myProducts",foreignKey:"categoryId"})
In what way i am able to get products with its images when I query for categories?
I Have tried with raw query
const resd=await db.sequelize.query("SELECT * FROM categories INNER JOIN products ON products.category=categories.id INNER JOIN productimages ON productimages.productId=products.id");
res.json({re:resd})
It works fine but it obviously display all things together
I want them in a nested pattern
Expected behavior:
{
"id": 1164,
"name": "Shirt",
"color": "red",
"myProducts":[{
"id":1,
"name": "raglan",
"price":"1200",
categoryId:1164,
"productImages":[{
id:12,
"image":"someimage.png",
"productId":1
}]
}]
CodePudding user response:
You can use nested include
option inside the first include
option:
const categoriesList = await Categories.findAll({
include:[{
model: Products,
as: 'myProducts',
include: [{
model: ProductImages,
as: 'productImages'
}]
}]
})
Though I don't recommend to load all-in-one considering a lot of images being loaded.