0

我正在尝试使用 MongoDB 后端构建 Ember 应用程序。Ember-data 现在支持嵌入对象,这使得能够将对象直接从嵌套文档中提取出来变得非常简单和棒。

我的问题是弄清楚如何将对象相互关联。

让我们看一个有学生和作业的教室的例子。

{
  students: [
    { name: 'Billy' },
    { name: 'Joe' }
  ],
  assignments: [
    { name: 'HW1', score: 70, student_name: 'Billy' },
    { name: 'HW2', score: 80, student_name: 'Billy' },
    { name: 'HW1', score: 60, student_name: 'Joe' },
    { name: 'HW2', score: 75, student_name: 'Joe' }
  ]
}

我将如何为他们建立关系,student以便我可以撤回他们的所有assignments

相关,我试图弄清楚如何关联嵌套在彼此内部的对象。我创建了一个jsbin试图在嵌套对象之间建立关系(向上而不是向下),但我不知道该怎么做。

4

1 回答 1

0

您可以使用下面的 repo 来指导您如何进行嵌入式关联。虽然他们没有使用 mongodb,但重要的是在 ember-data 方面,他们正在做嵌入式关联。

https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/controllers/contact_edit_controller.js

请注意,此处 App.PhoneNumber 嵌入在 App.Contact 中。但它应该让您了解如何解决您的问题。

App.Contact = DS.Model.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string'),
  email: DS.attr('string'),
  notes: DS.attr('string'),
  phoneNumbers: DS.hasMany('App.PhoneNumber'),
});

App.PhoneNumber = DS.Model.extend({
  number: DS.attr('string'),
  contact: DS.belongsTo('App.Contact')
});

https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/store.js

App.Adapter = DS.RESTAdapter.extend({
  bulkCommit: false
});

App.Adapter.map('App.Contact', {
  phoneNumbers: {embedded: 'always'}
});

App.Store = DS.Store.extend({
  revision: 12,
  adapter: App.Adapter.create()
});

https://github.com/dgeb/ember_data_example/blob/master/app/assets/javascripts/controllers/contact_edit_controller.js

App.ContactEditController = Em.ObjectController.extend({
 needs: ['contact'],

 startEditing: function() {
   // add the contact and its associated phone numbers to a local transaction
   var contact = this.get('content');
   var transaction = contact.get('store').transaction();
   transaction.add(contact);
   contact.get('phoneNumbers').forEach(function(phoneNumber) {
   transaction.add(phoneNumber);
 });
   this.transaction = transaction;
  },

  save: function() {
   this.transaction.commit();
  },

  addPhoneNumber: function() {
    this.get('content.phoneNumbers').createRecord();
  },

});
于 2013-03-17T18:02:46.103 回答