【问题标题】:Load multiple model data in same api call emberjs?在同一个api调用emberjs中加载多个模型数据?
【发布时间】:2018-11-15 00:17:03
【问题描述】:

这是我在 emberjs 中定义的两个模型

ma​​tch.js

import DS from 'ember-data';

export default DS.Model.extend({
  team: DS.belongsTo('team', {async:true}),
  opponent: DS.belongsTo('team', {async: true}),
  type: DS.attr('string'),
  squad: DS.attr('boolean')
});

team.js

import DS from 'ember-data';

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

我已经将比赛作为模型加载。在同一个 api 调用中,我还想为团队加载模型数据。我到目前为止的 api 响应是

{
  "meta":{
    "type":"match"
  },
  "data":[
    {
      "id":1119536,
      "type":"match",
      "attributes":{
        "id":1119536,
        "team":{
          "type":"team",
          "id":1,
          "attributes":{
            "id":1,
            "name":"England",
            "logo":null
          }
        },
        "opponent":{
          "type":"team",
          "id":3,
          "attributes":{
            "id":3,
            "name":"Pakistan",
            "logo":null
          }
        }
      }
    }
  ]
}

match 模型数据已正确加载,但我在team 数据方面遇到了同样的问题。响应来自浏览器中的网络,我已经使用浏览器上的 ember 插件检查了模型,团队数据未加载。如何使用同一个 api 调用来加载多个模型。

【问题讨论】:

    标签: ember.js ember-data json-api


    【解决方案1】:

    需要注意的几点:

    • 不要将id 放入attributes
    • 不要命名属性type。真的不要!这是一个保留关键字。
    • 关系不是属性,应该在relationships
    • 使用included 数组旁加载数据
    • ids 必须是字符串

    例如,这将是一个有效的负载:

    {
      "meta": {
        "type": "match"
      },
      "data": [
        {
          "id": "1119536",
          "type": "team",
          "attributes": {
            "match-type": "match"
          },
          "relationships": {
            "team": {
              "data": {
                "type": "team",
                "id": "1"
              }
            },
            "opponent": {
              "data": {
                "type": "team",
                "id": "3"
              }
            }
          }
        }
      ],
      "included": [
        {
          "type": "team",
          "id": "1",
          "attributes": {
            "name": "England",
            "logo": null
          }
        },
        {
          "type": "team",
          "id": "3",
          "attributes": {
            "name": "Pakistan",
            "logo": null
          }
        }
      ]
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多