如何包含嵌套关系?

时间:2015-12-10 17:31:15

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

http://jsonapi.org/format/#fetching-includes

文章属于作者。文章有很多评论。评论属于用户。

尝试了解如何包含嵌套关系。例如:https://www.foo.com/articles?include=comments

你会期望:

{
  data: [
    {
      id: 1,
      type: "articles",
      attributes: { ... },
      relationships: {
        author: { ... },
        comments: [{ ... }, { ... }],
      },
      ...
    },
    { ... }
  ]
  included: [
    {
      author: { ... },
      comment: { ... },
      comment: { ... }
    {
  ]
}

现在假设您想要包含撰写这些评论的用户。 https://www.foo.com/articles?include=comments.user

响应应该如下:

{
  data: [
    {
      id: 1,
      type: "articles",
      attributes: { ... },
      relationships: {
        author: { ... },
        comments: [{ ... }, { ... }]
      },
      ...
    },
    { ... }
  ]
  included: [
    {
      author: { ... },
      comment: { ... },
      comment: { ... },
      user: { ... },
      user: { ... }
    {
  ]
}

users(撰写评论的用户)是否也应该在relationship节点中,或者只在included节点中?

如果在relationship节点中。 user是否应嵌套在data.relationships.comments内?那怎么样?

1 个答案:

答案 0 :(得分:0)

根据Top Level文档,included字段应为Resource Objects数组。这意味着您的included字段应如下所示:

"included": [
    {
        "type": "author",
        "id": ...,
        "attributes": { ... },
        "relationships": { ... }
    }, {
        "type": "comment",
        "id": ...,
        "attributes": { ... },
        "relationships": { ... }
    }
]

同样根据Relationships文档,它应该(在加载侧边数据时)包含Resource Linkage data字段,在该字段中包含单个Resource IdentifierbelongsTo关系的情况下,hasMany关系或资源标识符对象的数组。

belongsTo资源标识符:

"relationships": {
    "author": {
        "links": { ... },
        "data": { "type": ..., "id": ... }
    },
    "comments": {
        "links": { ... },
        "data": [
            { "type": ..., "id": ... },
            { "type": ..., "id": ... }
        ]
    }
}