如何计算另一个 include sequelize 中的 include
How to count an include inside a another include sequelize
我有 3 个 table,我需要计算我的 table 订单有多少 Cupons,我的 table Cupons 属于我的 table 订单,并且我的 table 订单属于我的 table Afiliado,我需要获取所有 'Afiliates',并获取所有订单和订单的所有 Cupons 并计算 Cupons,我试过这种方式但没有没工作
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',
},
},
})
})
@编辑
它通过@Anatoly 评论解决,通过子查询,如果其他人有同样的问题,最后的解决方案
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"]
],
}
},
})
})
````
如果您想在某个Afiliados中获得多少Cupons,那么您可以尝试从Cupons开始以相反的方式进行:
return await Cupom.count({
include: [{
model: Orders,
required: true,
attributes: [],
as: 'Ordens',
where: {
// indicate the real PK field name here
afiliadosId: item.id
}
}]
})
如果您想获取订单详细信息,则需要使用子查询并删除 Cupom 的 include
选项:
return await Afiliados.findByPk(item.id, {
include: {
model: Orders,
as: 'Ordens',
attributes: {
include: [
[Sequelize.literal("SELECT COUNT(*) FROM Cupom where Cupom.order_id = Ordens.id)"), "CuponsCount"]
],
},
},
})
我有 3 个 table,我需要计算我的 table 订单有多少 Cupons,我的 table Cupons 属于我的 table 订单,并且我的 table 订单属于我的 table Afiliado,我需要获取所有 'Afiliates',并获取所有订单和订单的所有 Cupons 并计算 Cupons,我试过这种方式但没有没工作
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',
},
},
})
})
@编辑 它通过@Anatoly 评论解决,通过子查询,如果其他人有同样的问题,最后的解决方案
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"]
],
}
},
})
})
````
如果您想在某个Afiliados中获得多少Cupons,那么您可以尝试从Cupons开始以相反的方式进行:
return await Cupom.count({
include: [{
model: Orders,
required: true,
attributes: [],
as: 'Ordens',
where: {
// indicate the real PK field name here
afiliadosId: item.id
}
}]
})
如果您想获取订单详细信息,则需要使用子查询并删除 Cupom 的 include
选项:
return await Afiliados.findByPk(item.id, {
include: {
model: Orders,
as: 'Ordens',
attributes: {
include: [
[Sequelize.literal("SELECT COUNT(*) FROM Cupom where Cupom.order_id = Ordens.id)"), "CuponsCount"]
],
},
},
})