【问题标题】:Sequelize many-to-many M:N relationship not functioning. Error: 'SequelizeEagerLoadingError:${model1} is not associated to ${model2}'续集多对多 M:N 关系不起作用。错误:'SequelizeEagerLoadingError:${model1} 未关联到 ${model2}'
【发布时间】:2020-11-11 17:03:15
【问题描述】:

我正在尝试通过预定义的表 roleUsers 在用户和角色之间建立多对多关系。

const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING,
    phone: DataTypes.STRING,
    password: DataTypes.STRING,
    deletedAt: DataTypes.DATE,
  },

  const Role = sequelize.define('Role', {
    roleName: DataTypes.STRING,
  }, 

  const RoleUser = sequelize.define('RoleUser', {
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: User,
        key: 'id',
      },
    },
    roleId: {
      type: DataTypes.INTEGER,
      references: {
        model: Role,
        key: 'id',
      },
    },
  },

  Role.belongsToMany(User, {
    through: RoleUser,
    foreignKey: 'roleId',
    otherKey: 'userId',
    as: 'users',
  });
  User.belongsToMany(Role, {
    through: RoleUser,
    foreignKey: 'userId',
    otherKey: 'roleId',
    as: 'roles',
  });

但是,当我尝试调用这种关系(或任何其他 M:N 关系 - 1:Ms 和 1:1s 工作正常)时,如下所示

    const roles = await Role.findAll({
      include: [
        {
          model: User,
          as: 'users',
          through: RoleUser,
        },
      ],
    });

我收到以下错误

SequelizeEagerLoadingError: User is not associated to Role!

我通常尝试取出东西并以各种组合放回定义中定义的外键、其他键、别名以及改变我调用模型的方式(删除别名等)。我也尝试不在联结表中指定引用。

我的模型和关系被安排在不同的页面上,但它们都很好地结合在一起,因为我可以看到 1:M 关系运行良好,只是我的 M:M 关系搞砸了。如果有任何帮助,我将不胜感激!

【问题讨论】:

    标签: sequelize.js many-to-many associations eager-loading junction-table


    【解决方案1】:

    您已使用 through 表来关联用户和角色,因此表角色和用户表中不会有 foreignKey 列,如果您想在用户表中添加 role_id 而不是简单地创建列

        role_id: {
            type: DataTypes.INTEGER(),
            allowNull: true
        }
    

    比在用户表中添加role_id 和其他数据 设置角色如下user.setRoles(req.body.role_id) 这将在UserRoles 表中添加数据

    Roles.belongsToMany(Users, { through: 'UserRoles', foreignKey: 'role_id', otherKey: 'user_id' });
    Users.belongsToMany(Roles, { through: "UserRoles", foreignKey: "user_id", otherKey: "role_id" });
    UserRoles.belongsTo(Users, { foreignKey: 'user_id', targetKey: 'id' });
    UserRoles.belongsTo(Roles, { foreignKey: 'role_id', targetKey: 'id' });
    

    比尝试像下面这样的 api 来获取所有用户及其角色

                    let role = await sequelize.UserRoles.findAll({
                    include: [
                        {
                            model: sequelize.Users,
                            attributes: { exclude: ['password'] }
                        },
                        {
                            model: sequelize.Roles
                        }
                    ]
                });
    
                let result = error.OK;
                result.data = role;
    
                logger.info(result);
                return res.status(200).send(result)
    

    以上查询将返回如下数据

    "data": [
        {
            "user_id": 1,
            "role_id": 2,
            "createdAt": "2020-11-11T11:40:50.999Z",
            "updatedAt": "2020-11-11T11:40:50.999Z",
            "User": {
                "id": 1,
                "first_name": "admin1",
                "last_name": "Admin1",
                "user_name": "admin1",
                "email": "admin1@gmail.com"
                "role_id": 1,
                "user_type": "ADMIN",
                "createdAt": "2020-11-11T11:40:49.053Z",
                "updatedAt": "2020-11-11T11:40:49.053Z"
            },
            "Role": {
                "id": 1,
                "name": "ADMIN"
                "createdAt": "2020-11-11T11:37:47.638Z",
                "updatedAt": "2020-11-11T11:37:47.638Z"
            }
        }
    ],
    

    【讨论】:

    • 嗨,Arya,非常感谢您的详细回答,但仍然无法正常工作!我现在收到一个错误,User is not associated to RoleUser!
    【解决方案2】:

    如果其他人有此问题 - 我能找到解决此问题的唯一方法是在使用之前直接说明关系,而不是将其列在单独的模型/关系页面上。

    【讨论】:

      【解决方案3】:

      我想用别名 users 表示 User 就足以满足您的要求:

       const roles = await Role.findAll({
            include: [
              {
                model: User,
                as: 'users'
              },
            ],
          });
      

      【讨论】:

      • 她使用 through 连接两个表,因此不会与两个表直接关联
      • 您已经通过Role.belongsToMany(User 使用别名users 连接了它们
      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2020-09-05
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多