11

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.

4

1 回答 1

1

这是我当前项目的解决方案。请注意,有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 后端,顺便说一句)

于 2013-12-10T19:59:01.143 回答