我是 Backbone 关系新手,我不确定使用 HasMany 的正确方法是什么。
我有一个Parent
模型有很多children
(“许多”是指成千上万的孩子)。为了避免性能问题,我通过外键查询子项:/child/?parent=1
,而不是创建一个巨大的列表child_ids
in Parent
。但这似乎不是骨干关系的工作方式。
所以我想知道处理这个问题的正确方法是什么。
1,更改我的 json api 以包含父级中的子级 id 列表,然后按照 Backbone-relational 建议发送数千个 id:
url = function(models) {
return '/child/' + ( models ? 'set/' + _.pluck( models, 'id' ).join(';') + '/' : '');
}
// this will end up with a really long url: /child/set/1;2;3;4;...;9998;9999
2、重写Backbone-relational中的很多方法,让它处理这种情况。我的第一个想法是:
relations: [{
collectionOptions: function(model){
// I am not sure if I should use `this` to access my relation object
var relation = this;
return {
model: relation.relatedModel,
url: function(){
return relation.relatedModel.urlRoot + '?' + relation.collectionKey + '=' + model.id;
}
}
}
}]
// This seems work, but it can not be inherent by other model
// And in this case parent will have am empty children list at beginning.
// So parent.fetchRelated() won't fetch anything, I need call this url my self.
3、仅使用Backbone-relational作为Store,然后使用Collection来管理关系。
4、其他一些神奇的方式或模式或骨干框架
感谢帮助。
这是我当前项目的解决方案。注意Project
有许多评论、事件、文件和视频。这些关系及其反向关系在这些模型上定义:
Entities.Project = Backbone.RelationalModel.extend({
updateRelation: function(relation) {
var id = this.get('id'),
collection = this.get(relation);
return collection.fetch({ data: $.param({ project_id: id }) });
}
});
我将 REST 端点配置为采用充当连续“WHERE”子句的参数。所以project.updateRelation('comments')
将发送请求至/comments?project_id=4
我在服务器端有一些进一步的逻辑来过滤掉用户无权查看的内容。 (Laravel 后端,顺便说一句)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)