-
Notifications
You must be signed in to change notification settings - Fork 173
Adding related resource data
You can send related resource data along with the original resource. For example, you may wish to send a specific node, along with all its comments, all in the one JSON response.
The following discussion assumes the use of RESTful's JSON API formatter, but other formatters are also capable of including related resource data.
RESTful follows the JSON API specification for how to format related resource data: http://jsonapi.org/format/#fetching-includes
In order to add related resource data, you must add a public field to your resource which describes the relationship with the secondary resource. This step will add a relationships
section to the resulting JSON response, alongside each resource item's attributes
. This relationships data describes the type of related resource and its ID, but nothing more.
To obtain the full secondary resource in the JSON response, including its attributes etc, you must add the include
parameter in the URL.
An example URL would look like: /articles/1?include=comments
, which would request the data for article ID 1 plus all related comments.
There are two provided public field types for implementing related resources. Which you use depends on the nature of the relationship.
If your resource is for an entity which has a relationship to another entity, such as a node's author (from $node->uid), use \Drupal\restful\Plugin\resource\Field\ResourceFieldEntityReference
.
An example (that requires a collections:1.0 resource to have already been defined):
use Drupal\restful\Plugin\resource\Field\ResourceFieldEntityReference;
...
$public_fields['collection'] => array(
'property' => 'field_collection',
'class' => '\Drupal\restful\Plugin\resource\Field\ResourceFieldEntityReference',
'resource' => array(
'name' => 'collections',
'majorVersion' => 1,
'minorVersion' => 0,
),
),
Search the tests and sample resources included with RESTful for sample code using ResourceFieldEntityReference
.
This field type is useful when your resource has a custom relationship to another thing, that is not via an entity reference field. This resource field type's class allows you to define a callback which returns an ID to identify the relationship.
This is specially useful when adding a relationship to an entity based resource from a DB query, or vice versa. See an example of this in action in the example resource main:1.8
.
The class to use in this case is \Drupal\restful\Plugin\resource\Field\ResourceFieldReference
.