Ember 数据JSON-API hasMany:怎么样?

Ember Data JSON-API hasMany: How?

我熟悉旧的 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 和类型信息分开,防止命名空间冲突。

我还不明白如何用 JSON-API 格式建立 hasMany 关系。任何人都可以指出有关如何预期的文档或文章吗? examples on the JSON-API page 显示个人关系,但不显示 hasMany

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

我在 The JSON-API spec 中找到了答案。

每个模型都应该有一个 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"
          }
        }
      }
    }
  ]
}

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

1.使用 Related Resource Link:

一旦需要 hashMany 关系,Ember Data 将调用相关 link 的后端来获取所有关系。

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

2。使用 find-ids

只要需要 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"
                    }]
                }
            }
        }
    }]
}