Ember-Data recursive hasMany association

前端 未结 3 965
小鲜肉
小鲜肉 2021-01-31 12:03

Has anyone used ember-data to model a tree of data?

I would assume it would be something like:

Node = DS.Model.extend({
    children: DS.hasMany(Node),
          


        
相关标签:
3条回答
  • 2021-01-31 12:58

    This didn't work for me until I set up the inverse:

    App.Node = DS.Model.extend({
        children: DS.hasMany('App.Node', {inverse: 'parent'}),
        parent:   DS.belongsTo('App.Node', {inverse: 'children'}) });
    
    0 讨论(0)
  • 2021-01-31 12:58

    Not sure but as per example given in ember guide

    App.Post = DS.Model.extend({
      comments: DS.hasMany('App.Comment')
    });
    

    The JSON should encode the relationship as an array of IDs:

    {
      "post": {
        "comment_ids": [1, 2, 3]
      }
    }
    
    0 讨论(0)
  • 2021-01-31 13:03

    There are several little things that prevent your fiddle to work:

    • the DS.hasMany function asks for a String as argument. Don't forget the quotes: DS.hasMany('Node')

    • in the fixture definition, hasMany relationships should not be postfixed by _ids or anything. Just use the plain name. For instance: { id: 42, children: [2,3], parent_id: 17 }

    • the length property of DS.ManyArray should be accessed using the get function: root.get('children.length')

    • by default, the fixture adapter simulates an ajax call. The find query will populate the record after waiting for 50ms. In your fiddle, the root.get('children.length') call comes too early. You can configure the fixture adapter so that it makes synchronous call:

      App.store = DS.Store.create({
          revision: 4,
          adapter: DS.FixtureAdapter.create({
              simulateRemoteResponse: false
          })
      });
      

      Or you can load data to the store without any adapter:

      App.store.loadMany(App.Node, [
          { id: 1, children: [2, 3] },
          { id: 2, children: [], parent_id: 1 },
          { id: 3, children: [], parent_id: 1 }
      ]);
      
    • and last one: it seems like the Ember app should be declared in the global scope (no var), and Ember-data models should be declared in the app scope (replacing var Node = ... by App.Node = ...)

    Full example:

    App = Ember.Application.create();
    
    App.store = DS.Store.create({
        revision: 4
    });
    
    App.Node = DS.Model.extend({
        children: DS.hasMany('App.Node'),
        parent:   DS.belongsTo('App.Node')
    });
    
    App.store.loadMany(App.Node, [
        { id: 1, children: [2, 3] },
        { id: 2, children: [], parent_id: 1 },
        { id: 3, children: [], parent_id: 1 }
    ]);
    
    var root = App.store.find(App.Node, 1);
    
    alert(root.get('children'));
    alert(root.get('children.length'));
    
    0 讨论(0)
提交回复
热议问题