Backbone-relational hasmany best practices

馋奶兔 提交于 2019-12-22 03:58:14

问题


I am new to Backbone-relational, I am not sure what is the right way to use HasMany.

I have a Parent model which have many children (by "many" I mean thousands of children). In order to avoid performance issue, I query children by their foreign key: /child/?parent=1, instead of create a huge list of child_ids in Parent. But seems this is not the way Backbone-relational work.

So I am wondering what is the right way to handle this.

1, Change my json api to include list of child id in parent, then send thousands of ids as Backbone-relational recommend:

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, override many method in Backbone-relational, let it handle this situation. My first thought is :

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, Only use Backbone-relational as a Store, then use Collection to manage relations.

4, Some other magic way or pattern or backbone framework

Thanks for help.


回答1:


Here's the solution that I have going on my current project. Note that Project hasMany comments, events, files, and videos. Those relations and their reverse relations are defined on those models:

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 }) });
    }
});

I have the REST endpoint configured to take parameters that act as successive "WHERE" clauses. So project.updateRelation('comments') will send a request to /comments?project_id=4 I have some further logic on the server-side to filter out stuff the user has no right to see. (Laravel back-end, btw)



来源:https://stackoverflow.com/questions/15954406/backbone-relational-hasmany-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!