Sequelize删除多个关联

嗨,我有以下表格

models.User= sequelize.define("User", { name: { type: DataTypes.STRING, allowNull: false, unique: true } }); models.Group= sequelize.define("Group", { name: { type: DataTypes.STRING, allowNull: false, unique: true } }); db.User.belongsToMany(db.Group, { "through": "UsersGroup" }); db.Group.belongsToMany(db.User, { "through": "UsersGroup" }); 

有一种方法可以立即删除组中的多个用户,给定组名称以及要删除的名称(用户)?

喜欢:

 var groupName = 'Work'; var users = ['Alice','Bob'] 

所以我需要删除工作组和{Alice和Bob}之间的关联

使用"through": "UsersGroup"将自动创build一个新的模型用户组,但不会直接将其与用户和组相关联。 所以我要做的是创build一个新的sequelize模型用户组与任何属性和密钥,并定义到用户和组的关联。 然后,将“UsersGroup”string传递给belongsToMany而不是直接使用模型作为db.UsersGroup。

 models.UsersGroup = sequelize.define("UsersGroup", {}); db.UsersGroup.belongsTo(db.User); db.UsersGroup.belongsTo(db.Group); db.UsersGroup.findAll({attributes:['id'], include:[ {model: db.User, where: {name: {$in:['Alice','Bob']}}}, {mode: db.Group, where: {name: 'Work'}} ]}).then(function(toBeDeleted){ return db.UsersGroups.destroy({where:{id:{$in:toBeDeleted.map(function(d){ return d.id})}}}) }).then(function(){ .... }).catch(function(dbErr){throw err;}) 

你也可能想要检查if toBeDeleted.length > 0因为我记得当一个空数组传递时,sequelize变得有趣。

此外,如果你没有id作为用户组表中的主键,你可以很容易地修改上面的代码来使用user_id和group_id的组合 – 只需修改where语句。

另一种方法可以是分别select用户和组,并使用UsersGroups.destroy()结果集。 但是我更喜欢甚至从一个直通模式有一个协会。

如果你想删除只基于组名或用户名的关联,你可以使用removeAssociationremoveAssociations来做到这removeAssociation 在这里有一个removeAssociations

结束了(angular色 – >组,操作 – >用户)

  var role = JSON.parse(req.body.role); var actions = JSON.parse(req.body.actions); var actionNames = _.map(actions, function (action) { return action.name }); models.Role.findOne({ where: { name: role.name } }).then(function (_role) { if (_role == null) { res.status(500).send("role was not found"); } else { models.Action.findAll({ where: { name: actionNames } }).then(function (actionsToRemove) { if (actionsToRemove == null) { res.status(500).send("No action [" + action.name + "] was found"); } else { _role.removeActions(actionsToRemove).then(function (removedActions) { if (removedActions == null || removedActions != actions.length) { res.status(500).send(actions.length + " Action expected to be removed , but only [" + removedActions + "] were removed"); } else { res.send("" + removedActions); } }).catch(function (err) { throw err; }) } }) } }).catch(function (err) { res.status(500).send(err); });