【问题标题】:Creating row in both source and association with Sequelize many to many model在源和关联中创建行与 Sequelize 多对多模型
【发布时间】:2017-03-06 17:00:46
【问题描述】:

我在用户和组之间存在多对多关系。一个用户有很多组,一个组有很多用户。

我有一个名为 usersGroups 的用户表、组表和连接表。

我的用户模型:

'use strict';
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING,
    username: DataTypes.STRING,
    facebookId: DataTypes.STRING,
    password: DataTypes.STRING,
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Payment);
        User.hasMany(models.Friend, {foreignKey: 'userIdLink1', allowNull: false});
        User.belongsToMany(models.Group, { as: 'Groups', through: 'usersGroups', foreignKey: 'userId' });
      }
    },
    instanceMethods: {
      toJSON: function () {
        var values = Object.assign({}, this.get());

        delete values.password;
        return values;
      }
    }
  });
  return User;
};

我的小组模型

'use strict';
module.exports = function(sequelize, DataTypes) {
  var Group = sequelize.define('Group', {
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Group.belongsToMany(models.User, { as: 'Users', through: 'usersGroups', foreignKey: 'groupId' });
      }
    },
    instanceMethods: {
      toJSON: function () {
        var values = Object.assign({}, this.get());

        delete values.password;
        return values;
      }
    }
  });
  return Group;
};

当我尝试使用以下 2 种方法创建具有关联用户的新组时,它会创建一个新组但没有关联

const values = {
  userId: 1
}

const options = {
  include: db.Users
}

db.Group
  .create(values, options)
  .then( (group) => {
    res.send(group)
  }).catch(err => {
    res.status(500).send({err: err})
  })

db.Group
  .create()
  .then( (group) => {

    group.addUser({ userId: 1 }).then(result => {
        res.send(result)
    }).catch(err => {
        res.status(500).send({err: err})
    })

  }).catch(err => {
    res.status(500).send({err: err})
  })

【问题讨论】:

    标签: mysql sql node.js sequelize.js


    【解决方案1】:

    如果你只是想将用户分配给新创建的组,你需要使用addUser,就像你做的那样,但是这个方法接受第一个参数作为模型的实例或实例的ID,就像documentation说的那样

    与此关联的实例或实例的主键。

    所以你必须执行group.addUser(userId).then(...),在你的情况下是group.addUser(1).then(...)

    【讨论】:

    • 抱歉,我的帖子可能不够清楚,但我不想创建新用户,我想在 usersGroups 联结表中创建一个条目,该表引用新的 groupId 和现有的我传入的userId。
    • 我知道,我只是想简要介绍一下创建具有关联的模型,但我也包括了您的案例 - 将用户分配到组。我已经编辑了答案,所以现在只剩下这部分了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2016-11-02
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多