如何连接三个表 MySQL (Sequelize.js)

How to join three tables MySQL (Sequelize.js)

我有 3 个表:用户、部门和角色。我想获得指定部门的用户角色。用户可以为每个部门拥有不同的角色。我找不到在表之间创建链接的解决方案。对于 json 格式的想法,我会这样做:

{
    users: [
        {
            id: 1,
            email: "email@email.com",
            password: "password",
            name: "Mark",
            lastname: "Twain",
            departments: [
                {
                    id: 1,
                    name: "Department A",
                    role: "admin"
                },
                {
                    id: 2,
                    name: "Department B",
                    role: "user"
                }
            ] 
        },
        {
            id: 2,
            email: "email@email.com",
            password: "password",
            name: "Joe",
            lastname: "Ritter",
            departments: [
                {
                    id: 1,
                    name: "Department A",
                    role: "superadmin"
                },
                {
                    id: 2,
                    name: "Department B",
                    role: "user"
                },
                {
                    id: 3,
                    name: "Department C",
                    role: "user"
                }
            ] 
        }
    ]
}

有人知道如何把它变成 MySQL 吗?谢谢

如果一个用户在某个部门只能拥有一个角色(正如您在评论中提到的),您需要一个联结点 table UserDepartment 应该具有指向用户、部门和角色模型的链接,并且关联应该看起来像这样:

// M:N relationship between users and deparments
User.belongsToMany(Department, { through: UserDeparment });
// N:1 relationship that indicates a role for a certain pair of user-department
UserDepartment.belongsTo(Role);

为特定用户和部门获取角色的查询可能如下所示:

const userDepartment = UserDeparment.findOne({
  where: {
    userId,
    departmentId
  },
  attributes: [],
  include: [{
    model: Role
  }]
})

这会给你一个这样的对象:

{
  role: {
    id: 1,
    name: 'user'
  }
}