【问题标题】:How to include nested relationships?如何包含嵌套关系?
【发布时间】:2016-03-16 11:03:58
【问题描述】:

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

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

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

你会期望:

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

现在让我们说,您想包括编写这些 cmets 的用户。 https://www.foo.com/articles?include=comments.user

响应应该是这样的:

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

users(编写 cmets 的用户)也应该在 relationship 节点中,还是只在 included 节点中?

如果在relationship 节点中。 user 是否应该嵌套在 data.relationships.comments 中?看起来怎么样?

【问题讨论】:

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


    【解决方案1】:

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

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

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

    belongsTo资源标识符:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2014-11-08
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多