【问题标题】:Sequelize HasMany BelongsToMany removes old referenceSequelize HasMany BelongsToMany 删除旧参考
【发布时间】:2016-04-14 14:49:32
【问题描述】:

我遇到了一个问题,即在创建新实例时旧引用被删除。我将展示我的代码并举例说明,我做错了什么?

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

首先我自己创造一个兴趣

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

` //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() {
          }
        });
      });
    }
  });

` 当我创建第一个时,一切都很好,看:

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

到目前为止,一切都很好,在我添加第二个之后..

{"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"}]}}]}

当我创建具有相同兴趣的第二个实例时,将删除第一个实例的兴趣...

我做错了什么?

请帮忙!!!

【问题讨论】:

  • 如果您尝试进行多对多操作。您需要在 User 模型而不是 hasMany 上执行此操作。 Users.belongsToMany(models.Interest, {through: 'UsersInterest'});
  • @LT- 谢谢!!会尝试,如果有效,您可以将其写为获得声誉的答案。

标签: javascript sql node.js postgresql sequelize.js


【解决方案1】:

确实我做错了什么。感谢@LT- 的评论。 我将给出我更改的正确代码:

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

基本上,我在用户和兴趣上都添加了belongsToMany。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多