【发布时间】: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