0

I have the following architecture :

Users.hasMany(UserRoles)
UserRoles.belongsTo(Users)

Roles.hasMany(UserRoles)
UserRoles.belongsTo(Roles)

Roles.Users = Users.belongsToMany(Roles, { through: UserRoles, as: 'User_Role' })

I am getting this error :

Roles is not associated to Users!

The request I am making is like :

exports.getRole = async (ctx) => {

  const Role = await ctx.db.models.Roles.findOne({
    where: { id: ctx.request.body.RoleId },
    include: [{ model: ctx.db.models.Users }]
  })

  ctx.body = Role
}

I searched around to use the association or double include but that's not what I want as a response, because there are attributes which I don't need that come from UserRoles table.

{
 "id":"1"
 "role":"author",
 "UserRoles": {
  "id":"1",
  "roleId":"2"
  "user": { userdata }
 }
}

The response which I am trying to come up with is like this :

{
 "id":"1"
 "role":"author",
 "users": [ array fo users ]
}
Lu Blue
  • 335
  • 3
  • 10

2 Answers2

0

I found the answer here

The solution was using this way of belonging :

Parent.belongsToMany( Child, {
    as: [Relationship],
    through: [Parent_Child] //this can be string or a model,
    foreignKey: 'Parent_rowId'
});

Child.belongsToMany(Parent, {
    as: [Relationship2],
    through: [Parent_Child],
    foreignKey: 'Child_rowId'
});
Lu Blue
  • 335
  • 3
  • 10
0

Here below is a solution for many to many association in sequilize.

many to many association in node js sequelize many to many relationship implementation.

zshan4444
  • 380
  • 3
  • 7