简体   繁体   中英

Sequelize HasMany BelongsToMany removes old reference

I am having a problem that the old reference gets removed when I create a new instance. I will show my code and give an example, what am I doing wrong?

var Users = sequelize.define('Users', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: DataTypes.STRING, email: DataTypes.STRING }, { classMethods: { associate: function(models) { Users.hasMany(models.Interest,{ as: 'interests'}); } } } );

...

var Interest = sequelize.define('Interest', { category: DataTypes.STRING, value: DataTypes.STRING }, { classMethods: { associate: function(models) { Interest.belongsToMany(models.Users, {through: 'UsersInterest'}); } } });

first I create an interest alone

models.Interest.create({ value: data.value, category: data.category }).then(function(newInterest) { //allgood });

` //data holds the information the instance needs

models.Users.create({
  name: data.name,
  email: data.email

}).then(function(newUser) {
    //data interest contains the interest to find and add
    for (var i = 0; i < data.interests.length; i++) {
      models.Interest.findOne({
        where: { value: data.interests[i].value, category: data.interests[i].category},
      }).then(function(interest) {
          newUser.addInterest(interest).then(function() {
          }
        });
      });
    }
  });

` When I create the first one its all good, look:

{"user":{"id":1,"name":"Chelo","email":"chelo@intelli.com","interests":[{"value":"kitesurf","category":"sport"}]}}

until now, all good, after I add the second one..

{"user":{"id":1,"name":"Chelo","email":"chelo@intelli.com","interests":[]}} {"user":{"id":2,"name":"CACA Cavazzoli",email":"chelo@intelli.com","interests":[{"value":"kitesurf","category":"sport"}]}}]}

When I create a second instance with the same interest, then the interest from the first one is removed...

What am I doing wrong?

Please help!!!

Indeed I was doing something wrong. Thanks @LT- for your comment. I will give the correct code that I changed:

var Users = sequelize.define('Users', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, name: DataTypes.STRING, email: DataTypes.STRING }, { classMethods: { associate: function(models) { Users.belongsToMany(models.Interest,{ as: 'interests', through: 'UsersInterest'}); } } } );

Basically, I have added belongsToMany on both sides, on Users and on Interests.

Hope it helps.

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