简体   繁体   中英

Creating row in both source and association with Sequelize many to many model

I have a many to many relationship between a user and a group. A user has many groups and a group has many users.

I have a users table, a groups table and junction table called usersGroups.

My User model:

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

My group model

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

When I try create a new group with associated user with the following 2 methods, it creates a new group but no association

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

or

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

If you simply want to assign user to newly created group, you need to use addUser , just like you did, but this method accepts first parameter as instance of Model or ID of instance, just like the documentation says

An instance or primary key of instance to associate with this.

So you would have to perform group.addUser(userId).then(...) which in your case would be group.addUser(1).then(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM