如何在 Ember.js 中删除模型的 hasMany 关联中的所有记录
How to delete all records in a model's hasMany association in Ember.js
我有一个锦标赛模型,其中包含与之关联的比赛集合。假设我想一次销毁集合中的所有火柴,应该怎么做?这是我尝试过的:
var matches = tournament.get('matches').toArray();
for (var i = 0; i < matches.length; i++) {
matches[i].destroyRecord();
}
tournament.save().then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
这个 toArray
位似乎不正确,但它阻止了在我迭代它时修改可迭代对象。看来应该有办法一下子把这些比赛全部销毁,然后保存比赛。
是的,您不想迭代要从中删除项目的数组,因此您使用 toArray()
进行的操作是一种有效的方法。据我所知,没有 destroyAll() 或类似的函数。
您的问题表明您想要销毁比赛,而不仅仅是将它们从锦标赛中分离出来,这意味着要单独销毁每场比赛。 destroyRecord() 函数将记录标记为删除,然后通过适配器保存更改。
通常比赛将通过外键与锦标赛相关联,因此销毁每场比赛应该足以将其从锦标赛中移除,而不需要单独保存锦标赛,除非锦标赛上有其他派生属性,例如统计数据你还需要保存。
这里有一个小的 1 行技巧来完成它
tournament.get('matches').invoke("destroyRecord"); // deletes all records in 1 shot
如果您希望将其用作承诺
Ember.RSVP.all(tournament.get('matches').invoke("destroyRecord"))
.then(function(){
tournament.save()
.then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
});
我有一个锦标赛模型,其中包含与之关联的比赛集合。假设我想一次销毁集合中的所有火柴,应该怎么做?这是我尝试过的:
var matches = tournament.get('matches').toArray();
for (var i = 0; i < matches.length; i++) {
matches[i].destroyRecord();
}
tournament.save().then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
这个 toArray
位似乎不正确,但它阻止了在我迭代它时修改可迭代对象。看来应该有办法一下子把这些比赛全部销毁,然后保存比赛。
是的,您不想迭代要从中删除项目的数组,因此您使用 toArray()
进行的操作是一种有效的方法。据我所知,没有 destroyAll() 或类似的函数。
您的问题表明您想要销毁比赛,而不仅仅是将它们从锦标赛中分离出来,这意味着要单独销毁每场比赛。 destroyRecord() 函数将记录标记为删除,然后通过适配器保存更改。
通常比赛将通过外键与锦标赛相关联,因此销毁每场比赛应该足以将其从锦标赛中移除,而不需要单独保存锦标赛,除非锦标赛上有其他派生属性,例如统计数据你还需要保存。
这里有一个小的 1 行技巧来完成它
tournament.get('matches').invoke("destroyRecord"); // deletes all records in 1 shot
如果您希望将其用作承诺
Ember.RSVP.all(tournament.get('matches').invoke("destroyRecord"))
.then(function(){
tournament.save()
.then(function(tournament) {
that.transitionTo('tournaments.setup', tournament);
});
});