我熟悉旧的成员数据“旁写”模型,该模型如下所示:`
{
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方法是不同的。
首先(我喜欢这个),属性与id和类型信息分离,从而防止名称空间冲突。
我还不明白如何用JSON格式建立hasMany关系。有人能给我指一篇关于这是如何被期望的文档或文章吗?JSON页面上的示例显示单独的关系,但不显示hasMany。
如果你能用新的格式写出上面的例子,你就会回答我的问题。
发布于 2015-09-30 04:26:53
我在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"
}
}
}
}
]
}发布于 2018-10-30 13:11:12
FYI:如果您想稍后获取一个hashMany关系,那么您还有另外两个选项。
使用相关资源链接 1.
一旦需要hashMany关系,Ember数据将调用带有相关链接的后端,以获取所有关系。
{
"data": [{
...,
"relationships": {
"books": {
"links" {
"related": "http://example.com/books"
}
}
}
}]
}2.使用find-id
一旦需要hashMany关系,Ember数据将使用url调用后端以获取给定的ids。在本例中,它将是http://example.com/books?ids=1&ids=2
{
"data": [{
...,
"relationships": {
"books": {
"books": {
"data" [{
"id": "1",
"type": "book"
}, {
"id": "2",
"type": "book"
}]
}
}
}
}]
}https://stackoverflow.com/questions/32857605
复制相似问题