[英]Sequelize - Can't limit properly query with includes, using hasMany and belongsToMany associations
[英]Sequelize HasMany BelongsToMany removes old reference
我遇到一個問題,即在創建新實例時刪除舊引用。 我將展示我的代碼並舉例說明,我做錯了什么?
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"}]}}]}
當我創建具有相同興趣的第二個實例時,將刪除第一個實例的興趣...
我究竟做錯了什么?
請幫忙!!!
的確,我做錯了什么。 感謝@ 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。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.