包含关联对象¶
使用include查询参数,我们能在Response中返回关联对象的详情。同样,我们能在任何路由中(传统CRUD路由,或关系路由),以及任何返回数据的HTTP方法中使用include参数。
返回结果会多一个“included”的key。
例:
Request:
GET /persons/1?include=computers HTTP/1.1
Accept: application/vnd.api+json
Response:
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"data": {
"type": "person",
"id": "1",
"attributes": {
"display_name": "JEAN <jean@gmail.com>",
"birth_date": "1990-10-10"
},
"relationships": {
"computers": {
"data": [
{
"type": "computer",
"id": "1"
}
],
"links": {
"related": "/persons/1/computers",
"self": "/persons/1/relationships/computers"
}
}
},
"links": {
"self": "/persons/1"
}
},
"included": [
{
"type": "computer",
"id": "1",
"attributes": {
"serial": "Amstrad"
},
"relationships": {
"owner": {
"links": {
"related": "/computers/1/owner",
"self": "/computers/1/relationships/owner"
}
}
},
"links": {
"self": "/computers/1"
}
}
],
"links": {
"self": "/persons/1"
},
"jsonapi": {
"version": "1.0"
}
}
我们也能在relationship中使用include。
例:
Request:
GET /persons/1?include=computers.owner HTTP/1.1
Accept: application/vnd.api+json
Response:
HTTP/1.1 200 OK
Content-Type: application/vnd.api+json
{
"data": {
"type": "person",
"id": "1",
"attributes": {
"display_name": "JEAN <jean@gmail.com>",
"birth_date": "1990-10-10"
},
"relationships": {
"computers": {
"data": [
{
"type": "computer",
"id": "1"
}
],
"links": {
"related": "/persons/1/computers",
"self": "/persons/1/relationships/computers"
}
}
},
"links": {
"self": "/persons/1"
}
},
"included": [
{
"type": "computer",
"id": "1",
"attributes": {
"serial": "Amstrad"
},
"relationships": {
"owner": {
"data": {
"type": "person",
"id": "1"
},
"links": {
"related": "/computers/1/owner",
"self": "/computers/1/relationships/owner"
}
}
},
"links": {
"self": "/computers/1"
}
},
{
"type": "person",
"id": "1",
"attributes": {
"display_name": "JEAN <jean@gmail.com>",
"birth_date": "1990-10-10"
},
"relationships": {
"computers": {
"links": {
"related": "/persons/1/computers",
"self": "/persons/1/relationships/computers"
}
}
},
"links": {
"self": "/persons/1"
}
}
],
"links": {
"self": "/persons/1"
},
"jsonapi": {
"version": "1.0"
}
}
尽管例子比较搞笑,但我们只是为了解释用法。