在前面Ember.js 入門指南之三十八定義模型中介紹過模型之前的關系。主要包括一對一、一對多、多對多關系。但是還沒介紹兩個有關聯(lián)關系模型的更新、刪除等操作。
為了測試新建兩個模型類。
ember g model post
ember g model comment
// app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
// app/model/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
post: DS.belongsTo('post')
});
設置關聯(lián),關系的維護放在多的一方comment
上。
let post = this.store.peekRecord('post', 1);
let comment = this.store.createRecord('comment', {
post: post
});
comment.save();
保存之后post
會自動關聯(lián)到comment
上(保存post
的id
屬性值到post
屬性上)。
當然啦,你可以在從post
上設置關聯(lián)關系。比如下面的代碼:
let post = this.store.peekRecord('post', 1);
let comment = this.store.createRecord('comment', {
// 設置屬性值
});
// 手動吧對象設置到post數(shù)組中。(post是多的一方,comments屬性應該是保存關系的數(shù)組)
post.get('comments').pushObject(comment);
comment.save();
如果你學過Java里的hibernate框架我相信你很容易就能理解這段代碼。你可以想象,post
是一的一方,如果它要維護關系是不是要把與其關聯(lián)的comment
的id
保存到comments
屬性(數(shù)組)上,因為一個post
可以關聯(lián)多個comment
,所以comments
屬性應該是一個數(shù)組。
更新關聯(lián)關系與創(chuàng)建關聯(lián)關系幾乎是一樣的。也是首先獲取需要關聯(lián)的模型在設置它們的關聯(lián)關系。
let post = this.store.peekRecord('post', 100);
let comment = this.store.peekRecord('comment', 1);
comment.set('psot', post); // 重新設置comment與post的關系
comment.save(); // 保存關聯(lián)的關系
假設原來comment
關聯(lián)的post
是id
為1
的數(shù)據,現(xiàn)在重新更新為comment
關聯(lián)id
為100
的post
數(shù)據。
如果是從post
方更新,那么你可以像下面的代碼這樣:
let post = this.store.peekRecord('post', 100);
let comment this.store.peekRecord('comment', 1);
post.get('comments').pushObject(comment); // 設置關聯(lián)
post.save(); // 保存關聯(lián)
既然有新增關系自然也會有刪除關聯(lián)關系。
如果要移除兩個模型的關聯(lián)關系,只需要把關聯(lián)的屬性值設置為null
就可以了。
let comment = this.store.peekRecord('comment', 1);
comment.set('post', null); //解除關聯(lián)關系
comment.save();
當然你也可以從一的一方移除關聯(lián)關系。
let post = this.store.peekRecord('post', 1);
let comment = this.store.peekRecord('comment', 1);
post.get('comments').removeObject(comment); // 從關聯(lián)數(shù)組中移除comment
post.save();
從一的一方維護關系其實就是在維護關聯(lián)的數(shù)組元素。
只要Store改變了Handlebars模板就會自動更新頁面顯示的數(shù)據,并且在適當?shù)臅r期Ember Data會自動更新到服務器上。
有關于模型之間關系的維護就介紹到這里,它們之間關系的維護只有兩種方式,一種是用一的一方維護,另一種是用多的一方維護,相比來說,從一的一方維護更簡單。但是如果你需要一次性更新多個紀錄的關聯(lián)時使用第二種方式更加合適(都是針對數(shù)組操作)。
博文完整代碼放在Github(博文經過多次修改,博文上的代碼與github代碼可能有出入,不過影響不大!),如果你覺得博文對你有點用,請在github項目上給我點個star
吧。您的肯定對我來說是最大的動力??!
更多建議: