嵌套联接表的Sequelize查询问题

时间:2019-05-23 17:40:40

标签: sequelize.js

我使用Sequelize,我有3个模型:用户,角色,权限。

用户和角色通过联接表'user_role'关联。

角色和权限使用连接表'role_permission'关联。

无法成功查询特定用户的所有权限

请查看我的查询,看看您是否知道如何解决

用户模型

module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    username: DataTypes.STRING
  }, {
      underscored: true,
      timestamps: false
    });

  User.associate = function (models) {
    models.User.belongsToMany(models.Role, {
      through: 'user_role', unique: false,
      foreignKey: 'user_id', otherKey: 'role_id'
    });
  };

  return User;
};

角色模型:

module.exports = (sequelize, DataTypes) => {
  var Role = sequelize.define('Role', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    }
  }, {
      underscored: true,
      timestamps: false
    });

  Role.associate = function (models) {
    models.Role.belongsToMany(models.User, {
      through: 'user_role',
      unique: false, foreignKey: 'role_id', otherKey: 'user_id'
    });


    models.Role.belongsToMany(models.Permission, {
      through: 'role_permission', unique: false,
      foreignKey: 'role_id', otherKey: 'permission_id',
    });
  }
  return Role;
};

权限模型

module.exports = (sequelize, type) => {
  var Permission = sequelize.define('Permission', {
    id: {
      type: type.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: type.STRING
  }, {
      underscored: true,
      timestamps: false
    })

  Permission.associate = function (models) {
    models.Permission.belongsToMany(models.Role, {
      through: 'role_permission', unique: false,
      foreignKey: 'permission_id', otherKey: 'role_id'
    })
  };

  return Permission;
}

我需要查询以返回特定用户的所有权限。

我正在使用的查询不起作用:

let result = await models.User.findOne({
            where: { id: uid },
            include: [
                {
                    model: models.Role,
                    required: true,
                    attributes: ['id', 'name'],
                    include: [
                        {
                            model: models.Permission,
                            required: true,
                            attributes: ['id', 'name']
                        }]
                }
            ]
        });

0 个答案:

没有答案