第三方模型之间的关联化

时间:2019-11-06 15:30:03

标签: sequelize.js

我具有以下架构:

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

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

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

我收到此错误:

  

角色未与用户关联!

我正在发出的请求就像:

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
}

我四处搜索以使用关联或双重包含,但这不是我想要的响应,因为有些不需要的属性来自UserRoles表。

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

我想提出的答案是这样的:

{
 "id":"1"
 "role":"author",
 "users": [ array fo users ]
}

2 个答案:

答案 0 :(得分:0)

我找到了答案here

解决方案使用了这种归属方式:

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'
});

答案 1 :(得分:0)

以下是针对sequilize中许多关联的解决方案。

many to many association in node js使多对多关系实现得以实现。