Mysql
 sql >> Database >  >> RDS >> Mysql

Conteggio delle voci associate con Sequelize

Usa findAll() con include() e sequelize.fn() per il COUNT :

Location.findAll({
    attributes: { 
        include: [[Sequelize.fn("COUNT", Sequelize.col("sensors.id")), "sensorCount"]] 
    },
    include: [{
        model: Sensor, attributes: []
    }]
});

Oppure potresti dover aggiungere un group anche:

Location.findAll({
    attributes: { 
        include: [[Sequelize.fn("COUNT", Sequelize.col("sensors.id")), "sensorCount"]] 
    },
    include: [{
        model: Sensor, attributes: []
    }],
    group: ['Location.id']
})