How to add parent object to child in a one-to-may relationship in ember js

廉价感情. 提交于 2019-12-12 04:08:12

问题


I have two models in ember.js with a one-to-may relationship. Now I want to create a new child object and need to assign an associated parent object. I can't figure out how to do this. My models are defined with the following code:

model of parent-object

import DS from 'ember-data';

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

model of child-object

import DS from 'ember-data';

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

In the model()-method of the route create a child object.

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

and then query for the parent-object.

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

Then I tried to bind them together but anythig I tried failed. For example:

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

These things result in parent not having anything in child and child not having anything in parent. I also did some attempts with async promise resolving but with no success. It would be great if someone could post an example how to manage this.


回答1:


Basically this works as you expect. But you have a few minor errors:

  • Sometimes you use child and sometimes child-object. Same goes for parent.
  • findRecord returns a PromiseObject. You probably want to wait for the promise to resolve.
  • Its not addObject.

Also you can do it from both sides. Either set the parent:

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

Or you add the child to the children:

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

Maybe check out this twiddle.



来源:https://stackoverflow.com/questions/43482657/how-to-add-parent-object-to-child-in-a-one-to-may-relationship-in-ember-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!