mysql - Counting associated entries with Sequelize -
i have 2 tables, locations
, sensors
. each entry in sensors
has foreign key pointing locations
. using sequelize, how entries locations
, total count of entries in sensors
associated each entry in locations
?
raw sql:
select `locations`.*, count(`sensors`.`id`) `sensorcount` `locations` join `sensors` on `sensors`.`location`=`locations`.`id`; group `locations`.`id`;
models:
module.exports = function(sequelize, datatypes) { var location = sequelize.define("location", { id: { type: datatypes.integer.unsigned, primarykey: true }, name: datatypes.string(255) }, { classmethods: { associate: function(models) { location.hasmany(models.sensor, { foreignkey: "location" }); } } }); return location; }; module.exports = function(sequelize, datatypes) { var sensor = sequelize.define("sensor", { id: { type: datatypes.integer.unsigned, primarykey: true }, name: datatypes.string(255), type: { type: datatypes.integer.unsigned, references: { model: "sensor_types", key: "id" } }, location: { type: datatypes.integer.unsigned, references: { model: "locations", key: "id" } } }, { classmethods: { associate: function(models) { sensor.belongsto(models.location, { foreignkey: "location" }); sensor.belongsto(models.sensortype, { foreignkey: "type" }); } } }); return sensor; };
use findall()
include()
, sequelize.fn()
count
:
location.findall({ attributes: { include: [[sequelize.fn("count", sequelize.col("sensors.id")), "sensorcount"]] }, include: [{ model: sensor, attributes: [] }] });
or, may need add group
well:
location.findall({ attributes: { include: [[sequelize.fn("count", sequelize.col("sensors.id")), "sensorcount"]] }, include: [{ model: sensor, attributes: [] }], group: ['location.id'] })
Comments
Post a Comment