Counting associated entries with Sequelize

前端 未结 3 1686
挽巷
挽巷 2020-12-08 07:38

I have two tables, locations and sensors. Each entry in sensors has a foreign key pointing to locations. Using Sequelize,

3条回答
  •  旧时难觅i
    2020-12-08 08:17

    Use findAll() with include() and sequelize.fn() for the COUNT:

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

    Or, you may need to add a group as well:

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

提交回复
热议问题