我遇到了一个问题,当我创建一个新实例时,旧引用被删除了。我将展示我的代码并举例说明,我做错了什么?
var Users = sequelize.define('用户', {
ID: {
类型:DataTypes.INTEGER,
自动增量:真,
主键:真
},
名称:DataTypes.STRING,
电子邮件:DataTypes.STRING
},
{
类方法:{
关联:函数(模型){
Users.hasMany(models.Interest,{ as: 'interests'});
}
}
}
);
...
var Interest = sequelize.define('兴趣', {
类别:DataTypes.STRING,
值:DataTypes.STRING
}, {
类方法:{
关联:函数(模型){
Interest.belongsToMany(models.Users, {through: 'UsersInterest'});
}
}
});
首先我自己创造兴趣
models.Interest.create({
值(value):数据。值(value),
类别:data.category
}).then(函数(新兴趣){
//都好
});
` //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": “运动”}]}}
直到现在,一切都很好,在我添加第二个之后..
{"user":{"id":1,"name":"Chelo","email":"chelo@intelli.com","interests":[]}}
{"user":{"id":2,"name":"CACA Cavazzoli",email":"chelo@intelli.com","interests":[{"value":"kitesurf","category": “运动”}]}}]}
当我创建具有相同兴趣的第二个实例时,第一个实例的兴趣将被删除...
我做错了什么?
请帮忙!!!
最佳答案
确实我做错了什么。感谢@LT- 的评论。 我将给出我更改的正确代码:
var Users = sequelize.define('用户', {
ID: {
类型:DataTypes.INTEGER,
自动增量:真,
主键:真
},
名称:DataTypes.STRING,
电子邮件:DataTypes.STRING
},
{
类方法:{
关联:函数(模型){
Users.belongsToMany(models.Interest,{ as: 'interests', through: 'UsersInterest'});
}
}
}
);
基本上,我在用户和兴趣两边都添加了 belongsToMany。
希望对您有所帮助。
关于javascript - Sequelize HasMany BelongsToMany 删除旧引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36553304/