javascript – 保存关系的Ember数据
作者:互联网
我很难在ember数据中保存一对多的关系.我有这样的关系:
App.ParameterSet = DS.Model
name: DS.attr("string")
regions: DS.hasMany("App.Region")
App.Region = DS.Model
name: DS.attr("string")
如果我做这样的事情:
parameterSet = App.ParameterSet.find(5)
@transaction = @get("store").transaction()
@transaction.add(parameterSet)
region1 = App.Region.find(10)
region2 = App.Region.find(11)
parameterSet.set("name", "foo")
parameterSet.get("regions").pushObject(region)
@transaction.commit()
然后我想看到带有这样的有效负载的PUT请求:
api/ParameterSets/5
{parameterSet: {name: "foo", regionIds:[10, 11]}}
但相反,我得到了这个:
{parameterSet: {name: "foo"}}
我不关心从子节点到父节点之间的关系,但如果我将parameterSet:DS.belongsTo(“App.ParameterSet”)添加到App.Region模型,那么我会向区域url获取2个PUT请求以获取两个新关系这不是我想要的.
我想这是一个多对多的关系,我不确定是否支持,但有关如何实现我所描述的任何想法?谢谢
解决方法:
hasMany关系的序列化由json_serializer.js的addHasMany()方法处理.
以下注释包含在source code中:
The default REST semantics are to only add a has-many relationship if it
is embedded. If the relationship was initially loaded by ID, we assume that
that was done as a performance optimization, and that changes to the
has-many should be saved as foreign key changes on the child’s belongs-to
relationship.
要实现您的目标,一个选项是指示应该在您的适配器中嵌入关系.
App.Store = DS.Store.extend({
adapter: DS.RESTAdapter.extend({
serializer: DS.RESTSerializer.extend({
init: function() {
this._super();
this.map('App.ParameterSet', {
regions: { embedded: 'always' }
});
}
})
})
});
当然,现在你的后端需要在参数集的JSON中实际嵌入关联区域的JSON.如果您想保持原样,可以使用自定义序列化覆盖addHasMany().
App.Store = DS.Store.extend({
adapter: DS.RESTAdapter.extend({
serializer: DS.RESTSerializer.extend({
addHasMany: function(hash, record, key, relationship) {
// custom ...
}
})
})
});
标签:javascript,ember-js,ember-data 来源: https://codeday.me/bug/20190923/1815264.html