I'm trying to make a many to many relationship between users and roles through a predefined table 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',
});
However when I try to call this relationship (or any other M:N relationship - 1:Ms and 1:1s are working fine) as below
const roles = await Role.findAll({
include: [
{
model: User,
as: 'users',
through: RoleUser,
},
],
});
I'm getting the error below
SequelizeEagerLoadingError: User is not associated to Role!
I've generally tried taking things out and putting back in in various combinations the defined foreign keys, other keys, aliases in the definition and varying how I call the models (removing aliases, through etc). Also I tried not specifying the referencing in the junction table.
My models and relationships are arranged on separate pages, but they're all joining up fine as I can see the 1:M relationships are working fine, it's only my M:M relationships that are messing up. I would be so grateful for any help!