在Ember Data中分配hasMany关系

Edg*_*yJP 6 ember.js ember-data

我试图了解Ember Data模型,并试图将一个使用的对象集合分配给一个ember数据模型store.findAll()hasMany关系.

我定义了两个模型:

App.Leaf = DS.Model.extend({
    text: DS.attr('string'),
    branch: DS.belongsTo('App.Branch')
});

App.Branch = DS.Model.extend({
    lotsOfLeaves: DS.hasMany('App.Leaf')
});
Run Code Online (Sandbox Code Playgroud)

如果我将关系分配为 createRecord()

    App.store.loadMany(App.Leaf,[
        { id: 1, text: "Hello, I'm leaf 1", branch_id: 1 },
        { id: 2, text: "Hello, I'm leaf 2", branch_id: 1 }
    ]);
    var allLeaves = App.store.findAll(App.Leaf);
    var oneBranch = App.Branch.createRecord({ id: 1, lotsOfLeaves: allLeaves });
Run Code Online (Sandbox Code Playgroud)

然后它失败(静默)为oneBranch.get('lotsOfLeaves.length')0.

同样,如果我在关联后分配关系,它会无声地失败:

    var all = App.store.findAll(App.Leaf);
    oneBranch.set('lotsOfLeaves', all);
Run Code Online (Sandbox Code Playgroud)

我明白我可以使用pushObject()on oneBranch.get('lotsOfLeaves')来单独添加每个叶子,但这是唯一的方法吗?

小智 4

MutableArray 类还定义了一个 pushObjects() 方法,您应该能够使用该方法一次性添加所有对象。

文档位于:http ://docs.emberjs.com/symbols/Ember.MutableArray.html#method=pushObjects