gpt4 book ai didi

mysql - 使用 Sequelize 计算关联条目

转载 作者:IT老高 更新时间:2023-10-28 23:07:23 26 4
gpt4 key购买 nike

我有两张 table ,locationssensors . sensors 中的每个条目有一个指向 locations 的外键.使用 Sequelize,我如何从 locations 获取所有条目和 sensors 中的条目总数与 locations 中的每个条目相关联的?

原始 SQL:

SELECT 
`locations`.*,
COUNT(`sensors`.`id`) AS `sensorCount`
FROM `locations`
JOIN `sensors` ON `sensors`.`location`=`locations`.`id`;
GROUP BY `locations`.`id`;

型号:

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;
};

最佳答案

findAll()include()sequelize.fn() 一起用于 COUNT:

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

或者,您可能还需要添加 group:

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

关于mysql - 使用 Sequelize 计算关联条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37817808/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com