我有三种型号,用户,单位和排名
我选择将此模型建模为标准的多对多关系,将 Rank 属性存储在 UserUnit “直通”关系中。
模型定义的相关部分如下:
用户:
User.associate = function(models) {
models.User.belongsToMany(models.Unit, { through: 'UserUnit' });
};
单位:
Unit.associate = function(models) {
models.Unit.belongsToMany(models.User, { through: 'UserUnit' });
};
UserUnit:
UserUnit.associate = function(models) {
models.UserUnit.belongsTo(models.UserRank);
};
这将创建我认为是正确的数据库架构(尽管现在来看,我意识到UnitId / UserId / UserRankId可以是复合主键,而不是使用ID):
Table "UserUnits"
Column | Type | Collation | Nullable |
Default
------------+--------------------------+-----------+----------+-----------------------------------------
id | integer | | not null | nextval('"UserUnits_id_seq"'::regclass)
createdAt | timestamp with time zone | | not null |
updatedAt | timestamp with time zone | | not null |
UnitId | integer | | |
UserId | integer | | |
UserRankId | integer | | |
Indexes:
"UserUnits_pkey" PRIMARY KEY, btree (id)
"UserUnits_UnitId_UserId_key" UNIQUE CONSTRAINT, btree ("UnitId", "UserId")
Foreign-key constraints:
"UserUnits_UnitId_fkey" FOREIGN KEY ("UnitId") REFERENCES "Units"(id) ON UPDATE CASCADE ON DELETE CASCADE
"UserUnits_UserId_fkey" FOREIGN KEY ("UserId") REFERENCES "Users"(id) ON UPDATE CASCADE ON DELETE CASCADE
"UserUnits_UserRankId_fkey" FOREIGN KEY ("UserRankId") REFERENCES "UserRanks"(id) ON UPDATE CASCADE ON DELETE SET NULL
所以我的问题是这个
如何询问“向我显示所有单位用户及其相关排名” (不是 UserUnits 模型的ID,而是 UserRanks 模型的“ name”属性,因此会遍历关系)
我确切地知道如何使用SQL进行此操作,但是正在努力在Sequelize中将其可视化。如果有帮助,这就是我目前如何吸引所有单位用户的方式:
Unit: {
members(unit, args, { Models }) {
return Models.User.findAll({
include: [
{
model: Models.Unit,
where: { id: unit.id }
}
]
});
}
}
感谢您的任何帮助!