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之间关系的维护就介绍到这里,它们之间关系的维护只有两种方式,一种是用一的一方维护,另外一种是用多的一方维护,相比来讲,从多的一方维护更简单。可是若是你须要一次性更新多个纪录的关联时使用第二种方式更加合适(都是针对数组操做)。

相关文章
相关标签/搜索