Ember.js 入門指南——model的關聯關係處理

在前面《Ember.js 入門指南-模型定義》中介紹過模型以前的關係。主要包括一對1、一對多、多對多關係。可是還沒介紹兩個有關聯關係model的更新、刪除等操做。ubuntu

       爲了測試新建兩個modelvim

ember g model post
ember g model comment

 

1,建立關係記錄

//  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')
});

 

       設置關聯,關係的維護放在多的一方comment上。數組

let post = this.store.peekRecord('post', 1);
let comment = this.store.createRecord('comment', {
  post: post
});
comment.save();

       保存以後post會自動關聯到comment上(保存postid屬性值到post屬性上)。服務器

       固然啦,你也能夠在從post上設置關聯關係。好比下面的代碼:app

let post = this.store.peekRecord('post', 1);
let comment = this.store.createRecord('comment', {
       //  設置屬性值
});
//  手動吧對象設置到post數組中。(post是多的一方,comments屬性應該是保存關係的數組)
post.get('comments').pushObject(comment);
comment.save();

       若是你學過Java裏的hibernate框架我相信你很容易就能理解這段代碼。你能夠想象,post是一的一方,若是它要維護關係是否是要把與其關聯的commentid保存到comments屬性(數組)上,由於一個post能夠關聯多個comment,因此comments屬性應該是一個數組。框架

2更新已經存在的記錄

       更新關聯關係與建立關聯關係幾乎是同樣的。也是首先獲取須要關聯的model在設置它們的關聯關係。post

let post = this.store.peekRecord('post', 100);
let comment = this.store.peekRecord('comment', 1);
comment.set('psot', post);  //  從新設置comment與post的關係
comment.save();  //  保存關聯的關係

       假設原來comment關聯的postid1的數據,如今從新更新爲comment關聯id100post數據。測試

       若是是從post方更新,那麼你能夠像下面的代碼這樣:this

let post = this.store.peekRecord('post', 100);
let comment this.store.peekRecord('comment', 1);
post.get('comments').pushObject(comment);  // 設置關聯
post.save();  //  保存關聯

 

3,刪除關聯關係

       既然有新增關係天然也會有刪除關聯關係。spa

       若是要移除兩個model的關聯關係,只須要把關聯的屬性值設置爲null就能夠了。

let comment = this.store.peekRecord('comment', 1);
comment.set('post', null);  //解除關聯關係
comment.save();

       固然你也能夠從一的一方移除關聯關係。

let post = this.store.peekRecord('post', 1);
let comment = this.store.peekRecord('comment', 1);
post.get('comments').removeObject(comment);  // 從關聯數組中移除comment
post.save();

       從一的一方維護關係其實就是在維護關聯的數組元素。

      

       只要Store改變了Handlebars模板就會自動更新頁面顯示的數據,而且在適當的時期Ember Data會自動更新到服務器上。

 

有關於model之間關係的維護就介紹到這裏,它們之間關係的維護只有兩種方式,一種是用一的一方維護,另外一種是用多的一方維護,相比來講,從多的一方維護更簡單。可是若是你須要一次性更新多個紀錄的關聯時使用第二種方式更加合適(都是針對數組操做)。

相關文章
相關標籤/搜索