Ember.js 入门指南——model的关联关系处理

在前面《Ember.js 入门指南-模型定义》中介绍过模型之前的关系。主要包括一对一、一对多、多对多关系。但是还没介绍两个有关联关系model的更新、删除等操作。

       为了测试新建两个model

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上设置关联关系。比如下面的代码:

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在设置它们的关联关系。

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方更新,那么你可以像下面的代码这样:

let post = this.store.peekRecord('post', 100);
let comment this.store.peekRecord('comment', 1);
post.get('comments').pushObject(comment);  // 设置关联
post.save();  //  保存关联

 

3,删除关联关系

       既然有新增关系自然也会有删除关联关系。

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

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值