3

我熟悉旧的 ember-data “sideloading”模型,它看起来像这样:```

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

但新的 JSON-API 方法不同。

一方面,(我喜欢这个),属性与 id 和类型信息分开,防止命名空间冲突。

我还不明白如何hasMany与 JSON-API 格式建立关系。谁能指出我的文档或文章是如何预期的?JSON-API 页面上的示例显示了单独的关系,但不显示hasMany.

如果你能用新格式写出上面的例子,你就已经回答了我的问题。

4

2 回答 2

2

我在JSON-API 规范中找到了答案。

每个模型都应该有一个relationships键,它的值是一个对象,每个命名关系都有一个键,它还有一个data键,可以是单个对象,也可以是hasMany关系的数组。

通过提供一个included键作为顶级成员,我可以延迟加载实体。

在这种情况下,上面的示例将是:

{
  "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"
          }
        }
      }
    }
  ]
}
于 2015-09-30T04:26:53.783 回答
0

仅供参考:如果您想稍后获取 hashMany 关系,您还有另外两个选择。

1.使用相关资源链接

一旦需要 hashMany 关系,Ember Data 就会调用带有相关链接的后端来获取所有关系。

{
    "data": [{
        ...,
        "relationships": {
            "books": {
                "links" {
                    "related": "http://example.com/books"
                }
            }
        }
    }]
}

2.使用查找ID

一旦需要 hashMany 关系,Ember Data 就会使用 url 调用后端来获取给定的 id。在这个例子中,它将是http://example.com/books?ids=1&ids=2

{
    "data": [{
        ...,
        "relationships": {
            "books": {
                "books": {
                    "data" [{
                        "id": "1",
                        "type": "book"
                    }, {
                        "id": "2",
                        "type": "book"
                    }]
                }
            }
        }
    }]
}
于 2018-10-30T13:11:12.850 回答