国产chinesehdxxxx野外,国产av无码专区亚洲av琪琪,播放男人添女人下边视频,成人国产精品一区二区免费看,chinese丰满人妻videos

Ember model的關聯(lián)關系處理

2018-01-06 18:01 更新

在前面Ember.js 入門指南之三十八定義模型中介紹過模型之前的關系。主要包括一對一、一對多、多對多關系。但是還沒介紹兩個有關聯(lián)關系模型的更新、刪除等操作。

為了測試新建兩個模型類。

ember g model post
ember g model comment

1,創(chuàng)建關系記錄

//  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上(保存postid屬性值到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)的commentid保存到comments屬性(數(shù)組)上,因為一個post可以關聯(lián)多個comment,所以comments屬性應該是一個數(shù)組。

2,更新已經存在的記錄

更新關聯(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)的postid1的數(shù)據,現(xiàn)在重新更新為comment關聯(lián)id100post數(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)

3,刪除關聯(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吧。您的肯定對我來說是最大的動力??!

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號