简体   繁体   English

Sequelize HasMany BelongsToMany删除旧的参考

[英]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 `// data保存实例所需的信息

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. 感谢@ LT-的评论。 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. 基本上,我已在双方,用户和兴趣上添加了belongsToMany。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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