【问题标题】:How to add parent object to child in a one-to-may relationship in ember js如何在ember js中以一对多关系将父对象添加到子对象
【发布时间】:2017-04-18 21:40:19
【问题描述】:

我在 ember.js 中有两个具有一对一关系的模型。现在我想创建一个新的子对象并需要分配一个关联的父对象。我不知道该怎么做。我的模型是用以下代码定义的:

父对象的模型

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    children: DS.hasMany('child')
});

子对象模型

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    parent: DS.belongsTo('parent')
});

在路由的model()-方法中创建一个子对象。

var child = this.store.createRecord('child');

然后查询父对象。

var parent = this.findRecord('parent', 2);

然后我尝试将它们绑定在一起,但我尝试的任何方法都失败了。例如:

parent.get('child').addObject(child) // or
parent.get('child').pushObject(child) // or
child.set('parent', parent)

这些事情导致parentchild 中没有任何内容,而childparent 中没有任何内容。我也做了一些异步承诺解决的尝试,但没有成功。如果有人可以发布一个如何管理它的示例,那就太好了。

【问题讨论】:

    标签: javascript ember.js ember-data


    【解决方案1】:

    这基本上可以按您的预期工作。但是你有一些小错误:

    • 有时您使用child,有时使用child-objectparent 也是如此。
    • findRecord 返回 PromiseObject。您可能想等待承诺解决。
    • 不是addObject

    您也可以从两侧进行。设置父级:

    this.store.findRecord('parent-object', 2).then(parent => {
      const child = this.store.createRecord('child-object');
      child.set('parent', parent);
    });
    

    或者您将孩子添加到孩子中:

    this.store.findRecord('parent-object', 2).then(parent => {
      const child = this.store.createRecord('child-object');
      parent.get('children').pushObject(child);
    });
    

    也许看看this twiddle

    【讨论】:

    • 三A!这正是我一直在寻找的。我以为我也试过这个,但显然没有。也许值得一提的是,必须return 整个表达式以及child(第二个示例中的parent)才能将模型分配给控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多