我有一个 M:N 协会
const Group_User = sequelize.define("Group_User");
User.belongsToMany(Group, { through: Group_User });
Group.belongsToMany(User, { through: Group_User });
我还使用具有 id 和名称的模型 GroupRole 连接到该联结表。
Model
GroupRole.hasOne(Group_User);
Group_User.belongsTo(GroupRole);
我想要一个将返回 GroupRole.name 的查询
目前我有:
User.findOne({
where: {
id: userId
},
include: {
model: Group
}
});
返回:
{
"id": number,
"name", string,
"Groups": [
{
"id": number,
"Group_User": {
"UserId": number,
"GroupId": number,
"GroupRoleId": number
}
}
]
}
但我想将 GroupRoleId 解析为 GroupRole.name。当我尝试嵌套包含时,我得到:
GroupRole is not associated to Group
。
我做错了什么?
我正在尝试以下查询:
User.findOne({
where: {
id: userId
},
include: {
model: Group,
include: {
model: GroupRole
}
}
});
我期待的是:
{
"id": number,
"name", string,
"Groups": [
{
"id": number,
"Group_User": {
"UserId": number,
"GroupId": number,
"GroupRole": {
"id": number,
"name": string
}
}
}
]
}
看起来我正在尝试做的事情被称为超级多对多关系。
我需要为关联表指定一个id以及另外两个关系。
const Group_User = sequelize.define("Group_User", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull, false
});
User.belongsToMany(Group, { through: Group_User });
Group.belongsToMany(User, { through: Group_User });
Group.hasMany(Group_User);
User.hasMany(Group_User);
GroupRole.hasOne(Group_User);
Group_User.belongsTo(GroupRole);
这允许我使用 Group_User 作为包含,这样我就可以访问 GroupRole。
User.findOne({
where: {
id: userId
},
include: {
model: Group_User,
include: {
model: GroupRole
}
}
});