georoot
georoot

Reputation: 3617

Load multiple model data in same api call emberjs?

So here is two models that i have defined in emberjs

match.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')
});

and

team.js

import DS from 'ember-data';

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

I am already loading the match as a model. In the same api call i also want to load the model data for team. The api response that i have till now is

{
  "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
          }
        }
      }
    }
  ]
}

The match model data get loaded properly but i am having issues for the same with team data. The response is from network in browser and i already checked the model using ember plugin on browser that team data doesn't load. How can i use the same api call to load multiple models.

Upvotes: 1

Views: 206

Answers (1)

Lux
Lux

Reputation: 18240

a few things to notice:

  • dont put the id in attributes
  • dont name an attribute type. Really dont! It's a reserved keyword.
  • relationships are not attributes and should be under relationships
  • use the included array to sideload data
  • ids must be strings

so for example this would be a valid payload:

{
  "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
      }
    }
  ]
}

Upvotes: 4

Related Questions