使用联结表连接对查询进行序列化

问题描述 投票:0回答:1

我有一个 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
        }
      }
    }
  ]
}
sequelize.js
1个回答
0
投票

看起来我正在尝试做的事情被称为超级多对多关系。

https://sequelize.org/docs/v6/advanced-association-concepts/advanced-many-to-many/#the-best-of-both-worlds-the-super-many-to-many-relationship

我需要为关联表指定一个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
    }
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.