Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ <h1>json:api examples</h1>
<h3>Single resources</h3>
<ul>
<li><a href="resource.php">Basic example</a></li>
<li><a href="resource_nested_relations.php">Nested relations</a></li>
</ul>

<h3>Resources collections</h3>
Expand Down
41 changes: 41 additions & 0 deletions examples/resource_nested_relations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

use alsvanzelf\jsonapi;

ini_set('display_errors', 1);
error_reporting(-1);

require '../vendor/autoload.php';

/**
* preparing base data and nesting relationships
*/

require 'dataset.php';

$user = new user(42);

$flap = new jsonapi\resource('flap', 1);
$flap->add_data('color', 'orange');

$wing = new jsonapi\resource('wing', 1);
$wing->add_data('side', 'top');
$wing->add_relation('flap', $flap);

$ship = new jsonapi\resource('ship', 5);
$ship->add_data('name', 'Heart of Gold');
$ship->add_relation('wing', $wing);

/**
* building up the json response
*/

$jsonapi = new jsonapi\resource($type='user', $user->id);
$jsonapi->fill_data($user);
$jsonapi->add_relation('ship', $ship);

/**
* sending the response
*/

$jsonapi->send_response();
16 changes: 15 additions & 1 deletion src/response.php
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,28 @@ public function add_included_resource(\alsvanzelf\jsonapi\resource $resource) {
}

$resource_array = $resource_array['data'];
unset($resource_array['relationships'], $resource_array['meta']);

$key = $resource_array['type'].'/'.$resource_array['id'];

$this->included_data[$key] = $resource_array;

// make a backup of the actual resource, to pass on to a collection
$this->included_resources[$key] = $resource;

// allow nesting relationshios
foreach ($resource->get_included_resources() as $included_resource) {
if (empty($included_resource->primary_id)) {
continue;
}

$included_key = $included_resource->primary_type.'/'.$included_resource->primary_id;

$this->included_resources[$included_key] = $included_resource;

$included_array = $included_resource->get_array();
$included_array = $included_array['data'];
$this->included_data[$included_key] = $included_array;
}
}

/**
Expand Down