Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Data JSON-API hasMany: How?

I'm familiar with the old ember-data "sideloading" model, which would look like this: ```

{
  authors:[
    {id:1, name:"Ernest", type: 'author', books: [1,2]
  ],
  books: [
    {id:1, name: "For whom the bell tolls", type: 'book', author:1},
    {id:2, name: "Farewell To Arms", type: 'book', author:1}
  ]
}

But the new JSON-API method is different.

For one thing, (and I like this), attributes are separated from the id and type information, preventing namespace collisions.

I don't yet understand how to do a hasMany relationship with the JSON-API format. Can anyone point me to a doc or article on how this is expected? The examples on the JSON-API page show individual relationships, but not hasMany.

If you could write the above example in the new format, you'd have answered my question.

like image 938
DanF Avatar asked Mar 12 '26 04:03

DanF


1 Answers

I found the answer in The JSON-API spec.

Each model should have a relationships key, whose value is an object with a key for each named relationship, which also has a data key that can be either a single object or an array for a hasMany relationship.

By providing an included key as top-level member, I can lazy load the entities.

In this case, the above example would be:

{
  "data": [
    {
      "id": 1,
      "type": "author",
      "attributes": {
        "name": "Ernest"
      },
      "relationships": {
        "books": {
          "data": [
            {
              "id": "1",
              "type": "book"
            },
            {
              "id": "2",
              "type": "book"
            }
          ]
        }
      }
    }
  ],
  "included": [
    {
      "id": 1,
      "type": "book",
      "attributes": {
        "name": "For Whom the Bell Tolls"
      },
      "relationships": {
        "author": {
          "data": {
            "id": 1,
            "type": "author"
          }
        }
      }
    },
    {
      "id": 2,
      "type": "book",
      "attributes": {
        "name": "Farewell to Arms"
      },
      "relationships": {
        "author": {
          "data": {
            "id": 1,
            "type": "author"
          }
        }
      }
    }
  ]
}
like image 105
DanF Avatar answered Mar 13 '26 23:03

DanF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!