gpt4 book ai didi

ember.js - 删除与 ember-data 关联的模型

转载 作者:行者123 更新时间:2023-12-02 14:08:57 25 4
gpt4 key购买 nike

我有两个模型:

App.User = DS.Model.create({
comments: DS.hasMany('App.Comment')
});

App.Comment = DS.Model.create({
user: DS.belongsTo('App.User')
});

当删除用户时,它也会删除后端的所有评论,因此我应该从客户端身份映射中删除它们。

我从另一个地方列出了系统上的所有评论,因此删除用户后它只会崩溃。

有什么方法可以指定这种关联的依赖关系吗?谢谢!

最佳答案

当我想实现这种行为时,我使用 mixin。我的模型定义如下:

App.Post = DS.Model.extend(App.DeletesDependentRelationships, {
dependentRelationships: ['comments'],

comments: DS.hasMany('App.Comment'),
author: DS.belongsTo('App.User')
});

App.User = DS.Model.extend();

App.Comment = DS.Model.extend({
post: DS.belongsTo('App.Post')
});

mixin 本身:

App.DeletesDependentRelationships = Ember.Mixin.create({

// an array of relationship names to delete
dependentRelationships: null,

// set to 'delete' or 'unload' depending on whether or not you want
// to actually send the deletions to the server
deleteMethod: 'unload',

deleteRecord: function() {
var transaction = this.get('store').transaction();
transaction.add(this);
this.deleteDependentRelationships(transaction);
this._super();
},

deleteDependentRelationships: function(transaction) {
var self = this;
var klass = Ember.get(this.constructor.toString());
var fields = Ember.get(klass, 'fields');

this.get('dependentRelationships').forEach(function(name) {
var relationshipType = fields.get(name);
switch(relationshipType) {
case 'belongsTo': return self.deleteBelongsToRelationship(name, transaction);
case 'hasMany': return self.deleteHasManyRelationship(name, transaction);
}
});
},

deleteBelongsToRelationship: function(name, transaction) {
var record = this.get(name);
if (record) this.deleteOrUnloadRecord(record, transaction);
},

deleteHasManyRelationship: function(key, transaction) {
var self = this;

// deleting from a RecordArray doesn't play well with forEach,
// so convert to a normal array first
this.get(key).toArray().forEach(function(record) {
self.deleteOrUnloadRecord(record, transaction);
});
},

deleteOrUnloadRecord: function(record, transaction) {
var deleteMethod = this.get('deleteMethod');
if (deleteMethod === 'delete') {
transaction.add(record);
record.deleteRecord();
}
else if (deleteMethod === 'unload') {
var store = this.get('store');
store.unloadRecord(record);
}
}
});

请注意,您可以通过 deleteMethod 指定是否要向 API 发送 DELETE 请求。如果您的后端配置为自动删除相关记录,那么您将需要使用默认值。

这是一个jsfiddle这表明它正在发挥作用。

关于ember.js - 删除与 ember-data 关联的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15177723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com