我有两个表Users
和RepairCenters
,它们通过repairCentersUsers
表具有多对多关系。使用Sequelize,如何从Users
中获取所有条目,这些条目按与RepairCenters
关联的User
的数量和由分页的RepairCenter.name
进行排序?
模型
module.exports = (sequelize, DataTypes) => {
const Users = sequelize.define(
"Users",
{
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: "Name cannot be empty."
},
notNull: {
args: true,
msg: "Name cannot be null."
}
}
}
},
);
Users.associate = models => {
Users.belongsToMany(models.RepairCenters, {
as: "RepairCenters",
through: "repairCentersUsers",
foreignKey: "userId"
});
};
return Users;
};
module.exports = (sequelize, DataTypes) => {
const RepairCenters = sequelize.define("RepairCenters", {
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: {
args: true,
msg: "Name cannot be empty."
},
notNull: {
args: true,
msg: "Name cannot be null."
}
}
}
});
RepairCenters.associate = models => {
RepairCenters.belongsToMany(models.Users, {
as: "Users",
through: "repairCentersUsers",
foreignKey: "repairCenterId"
});
};
return RepairCenters;
};
我尝试过的查询
let { count, rows } = await Users.findAndCountAll({
offset: (page - 1) * length,
limit: length,
attributes: {
include: [
[
Sequelize.literal(
"(SELECT COUNT(*) FROM [repairCentersUsers] WHERE [repairCentersUsers].[userId] = [Users].[id])"
),
"RepairCentersCount"
]
]
},
include: [{ model: RepairCenters, as: "RepairCenters" }],
order: [
[Sequelize.literal("RepairCentersCount"), orderDirection],
[RepairCenters, "name", orderDirection]
],
distinct: true
});
这将产生以下SQL:
SELECT [Users].*,
[RepairCenters].[id] AS [RepairCenters.id],
[RepairCenters].[name] AS [RepairCenters.name],
[RepairCenters->repairCentersUsers].[createdAt] AS [RepairCenters.repairCentersUsers.createdAt],
[RepairCenters->repairCentersUsers].[updatedAt] AS [RepairCenters.repairCentersUsers.updatedAt],
[RepairCenters->repairCentersUsers].[repairCenterId] AS [RepairCenters.repairCentersUsers.repairCenterId],
[RepairCenters->repairCentersUsers].[userId] AS [RepairCenters.repairCentersUsers.userId]
FROM (SELECT [Users].[id],
[Users].[name],
(SELECT COUNT(*)
FROM [repairCentersUsers]
WHERE [repairCentersUsers].[userId] = [Users].[id]) AS [RepairCentersCount]
FROM [Users] AS [Users]
ORDER BY RepairCentersCount DESC OFFSET 0 ROWS FETCH NEXT 25 ROWS ONLY) AS [Users] LEFT OUTER JOIN ( [repairCentersUsers] AS [RepairCenters->repairCentersUsers]
INNER JOIN [RepairCenters] AS [RepairCenters]
ON [RepairCenters].[id] = [RepairCenters->repairCentersUsers].[repairCenterId])
ON [Users].[id] = [RepairCenters->repairCentersUsers].[userId]
ORDER BY RepairCentersCount DESC,
[RepairCenters].[name] DESC;
问题在于ORDER BY, OFFSET AND LIMIT
和RepairCenters
在子查询中。如何将ORDER BY, OFFSET AND LIMIT
置于此子查询的外部?