我遇到的问题是,在创建新实例时会删除旧引用。我将展示我的代码并举例说明,我做错了什么?
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"}]}}]}
当我创建具有相同兴趣的第二个实例时,将删除第一个实例的兴趣...
我做错了什么?
请帮助!!!
答案 0 :(得分:0)
确实我做错了什么。感谢@ 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。
希望它有所帮助。