Ember不会保留belongsTo数据

时间:2016-11-09 05:56:19

标签: javascript ember.js ember-data ember-cli

我使用Ember 2.4.6和Ember的JSONApiAdapter获取数据并将数据发送到节点服务器。

我有以下标签模型:

import DS from 'ember-data';

export default DS.Model.extend({
  label: DS.attr('string'),
  isRoot: DS.attr('boolean', {defaultValue: false'}),
  parent: DS.belongsTo('tag') //belongs to self type
});

这里的逻辑是用户可以为给定的根标签输入多个子标签。为了保存子标签和根标签,我使用标签服务的保存方法。标签服务的保存方法如下

import Ember from 'ember';

export default Ember.Service.extend({

  //Some other code

  save: function(parent, children){
    return parent.save().then(response => {
      return children.map(tag => {
        tag.set('parent', response);
        return tag.save();
      });
    });
  }
});

现在的问题是,当我为根标签说五个子标签时,这种关系只会持久化为最后一个标签,即第五个标签。

我为one父标记创建了五个标记twothreefourfiveroot。然后,当从标签服务调用save方法时,理想情况下应将以下数据发送到服务器。

{data: {id: 1, type: 'tags', attributes: {label: "root", "is-root": true}, relationships: {parent: {data: null}}}}
{data: {id: 2, type: 'tags', attributes: {label: "one", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}
{data: {id: 3, type: 'tags', attributes: {label: "two", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}
{data: {id: 4, type: 'tags', attributes: {label: "three", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}
{data: {id: 5, type: 'tags', attributes: {label: "four", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}
{data: {id: 6, type: 'tags', attributes: {label: "five", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}

但是以下信息将转到服务器

{data: {id: 1, type: 'tags', attributes: {label: "root", "is-root": true}, relationships: {parent: {data: null}}}}
{data: {id: 2, type: 'tags', attributes: {label: "one", "is-root": false}, relationships: {parent: {data: null}}}}
{data: {id: 3, type: 'tags', attributes: {label: "two", "is-root": false}, relationships: {parent: {data: null}}}}
{data: {id: 4, type: 'tags', attributes: {label: "three", "is-root": false}, relationships: {parent: {data: null}}}}
{data: {id: 5, type: 'tags', attributes: {label: "four", "is-root": false}, relationships: {parent: {data: null}}}}
{data: {id: 6, type: 'tags', attributes: {label: "five", "is-root": false}, relationships: {parent: {data: {id: 1, type: "tags"}}}}}

仅为最后一个标签发送belongsTo信息,而对于所有其他标签,父数据将被遗漏。

无法完全理解为什么会这样。请在这里建议我做错了什么。

1 个答案:

答案 0 :(得分:0)

在您的代码模型中,试试这个:

import DS from 'ember-data';

export default DS.Model.extend({
  label: DS.attr('string'),
  isRoot: DS.attr('boolean', {defaultValue: false}),
  parent: DS.belongsTo('tag', {inverse: null})
});

您可以在此处获得有关自反关系的更多信息:https://guides.emberjs.com/v2.9.0/models/relationships/#toc_reflexive-relations

从页面:

  

当你想要定义一个自反关系(一个有一个模型的模型)   与自身的关系),你必须明确定义逆   关系。如果没有反比关系,那么你可以设置   反向为空。