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')
});
我想出了添加新的联系人记录
答案 0 :(得分:5)
hasMany
关系可以通过addObject
,addObjects
或removeObject
来操纵。
contact.get('addresses').pushObject(address);
contact.get('addresses').removeObject(address);
您还可以在地址
上设置联系人address.set('contact', contact);
address.set('contact', null);
此外,您还注意到您应该使用单数形式进行belongsTo关联(contact
而不是contacts
):
App.Address = DS.Model.extend({
street: attr('string'),
country: attr('string'),
contact: belongsTo('App.Contact')
});
答案 1 :(得分: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