3

JSFiddle - http://jsfiddle.net/9gA4y/1/

我有以下模型:

contact => (many2many) => tags
contact => (one2many) => address

Ember 数据模型:

App.Contact = DS.Model.extend({
  name: attr('string'),  
  tags: hasMany('App.Tag'),
  addresses: hasMany('App.Address')
});

App.Address = DS.Model.extend({
  street: attr('string'),
  country: attr('string'),
  contacts: belongsTo('App.Contact')
})
App.Tag = DS.Model.extend({
  name: attr('string'),
  contacts: hasMany('App.Contact')
});

我想出了添加新的联系人记录

  • 如何将现有的地址关联到新创建的联系人。(一二多)
  • 如何将现有的标签关联到新创建的联系人。(多 2 多)
  • 如何删除现有联系人中的关联。
4

2 回答 2

5

hasMany可以通过 或 来addObject操纵addObjects关系removeObject

contact.get('addresses').pushObject(address);
contact.get('addresses').removeObject(address);

您还可以在地址上设置联系人

address.set('contact', contact);
address.set('contact', null);

此外,您注意到您应该对 belongsTo 关联使用单数形式(contactnot contacts):

App.Address = DS.Model.extend({
  street: attr('string'),
  country: attr('string'),
  contact: belongsTo('App.Contact')
});
于 2013-03-19T17:58:18.927 回答
3

尝试:

var contact = App.Contact.find(1),
    address = App.Address.find(1),
    tag = App.Tag.find(1);

contact.get('addresses').addObject(address);
contact.get('tags').addObject(tag);

this.get('store').commit(); //saves address and tag to contact

contact.get('tags').removeObject(tag);

this.get('store').commit(); //removes tag from contact
于 2013-03-17T19:00:51.193 回答