'How to count an include inside a another include sequelize
I have 3 tables, and i need to count how much Cupons my table orders have, my table Cupons belongs to my table orders, and my table orders belong to my table Afiliado, i need to fetch all 'Afiliates', and get all Orders and all Cupons of the order and count the Cupons, i tried this way but doesn't work
var Afiliadosorders = afiliados.map(async (item) => {
return await Afiliados.findByPk(item.id, {
include: {
model: Orders,
as: 'Ordens',
attributes: {
include: [
'order_id'
[Sequelize.fn("COUNT", Sequelize.col("Cupons.id")), "CuponsCount"]
],
separate:true,
limit: 1
},
include: {
model: Cupom,
as: 'Cupons',
},
},
})
})
@EDIT It's solved with the @Anatoly comment, with subquery, the finally solution if somebody else have the same issue
var Afiliadosorders = afiliados.map(async (item) => {
return await Afiliados.findByPk(item.id, {
include: {
model: Orders,
as: 'Ordens',
required: true,
attributes: {
include: [
[Sequelize.literal('(SELECT COUNT(*) FROM cupom where cupom.order_id = "Ordens"."id")'), "Total_Cupons"]
],
}
},
})
})
````
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
