Sequelize - Counting the same association twice under different conditions

Viewed 1490

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 Invoices AS Invoices ON Customer.id = Invoices.CustomerId AND Invoices.isArchived = 0
LEFT OUTER JOIN Invoices AS Invoices ON Customer.id = Invoices.CustomerId AND Invoices.isArchived = 0 AND Invoices.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 Invoices AS Invoices ON Customer.id = Invoices.CustomerId AND Invoices.isArchived = 0
LEFT OUTER JOIN Invoices AS UnpaidInvoices ON Customer.id = Invoices.CustomerId AND Invoices.isArchived = 0 AND Invoices.status = 'UNPAID'

1 Answers

I typically just join once and then use a CASE statement with SUM instead of using COUNT - the rows are all joined is why you get the same for both.

attributes: {
  include: [
    // count paid using case/sum via `status` != 'UNPAID'
    [ sequelize.fn('sum', sequelize.literal("CASE WHEN (`Invoices`.`status` != 'UNPAID' THEN 1 ELSE 0 END")), 'paid_count' ],
    // count unpaid using case/sum via `status` = 'UNPAID'
    [ sequelize.fn('sum', sequelize.literal("CASE WHEN (`Invoices`.`status` = 'UNPAID' THEN 1 ELSE 0 END")), 'unpaid_count' ],
  ],
  // ...
},
Related