I'm trying to fetch two counts of records in an associated table based on different parameters:
// Models
var Customer = sequelize.define('Customer', {
name: DataTypes.STRING,
});
var Invoice = sequelize.define('Invoice', {
invoiceRef: DataTypes.STRING,
status: {
type: DataTypes.ENUM,
values: ['UNPAID', 'PAID'],
defaultValue: 'UNPAID'
},
isArchived: {
type: DataTypes.BOOLEAN,
defaultValue: false
},
});
Invoice.associate = function(models) {
Invoice.belongsTo(models.Customer);
}
Customer.associate = function (models) {
Customer.hasMany(models.Invoice);
}
// Query
Customer.findAll({
attributes: {
include: [
[models.Sequelize.fn("COUNT", models.Sequelize.fn("DISTINCT", models.Sequelize.col("Invoices.id"))), "totalInvoices"],
[models.Sequelize.fn("COUNT", models.Sequelize.fn("DISTINCT", models.Sequelize.col("UnpaidInvoices.id"))), "unpaidInvoices"]
]
},
include: [
{
model: models.Invoice,
where: { isArchived: false },
attributes: [],
required: false
},
{
model: models.Invoice,
where: { isArchived: false, status: 'UNPAID' },
attributes: [],
required: false
},
],
group: ['Customer.id']
})
The issue is that when including the same associated table multiple times, Sequelize assigns the same name to both instances of the table in the SQL query:
LEFT OUTER JOIN
InvoicesASInvoicesONCustomer.id=Invoices.CustomerIdANDInvoices.isArchived= 0
LEFT OUTER JOINInvoicesASInvoicesONCustomer.id=Invoices.CustomerIdANDInvoices.isArchived= 0 ANDInvoices.status= 'UNPAID'
Is there any way to specify a different name to use for the joined table in the query? For example:
LEFT OUTER JOIN
InvoicesASInvoicesONCustomer.id=Invoices.CustomerIdANDInvoices.isArchived= 0
LEFT OUTER JOINInvoicesASUnpaidInvoicesONCustomer.id=Invoices.CustomerIdANDInvoices.isArchived= 0 ANDInvoices.status= 'UNPAID'