Use include for relations

This commit is contained in:
Joseph Cohen
2015-02-23 00:00:20 -06:00
parent 683dccbfac
commit cdd31ed05d
4 changed files with 61 additions and 13 deletions

View File

@@ -4,7 +4,6 @@ Route::api(['after' => 'allowed_domains', 'namespace' => 'CachetHQ\Cachet\Http\C
// Components
Route::get('components', 'ComponentController@getComponents');
Route::get('components/{id}', 'ComponentController@getComponent');
Route::get('components/{id}/incidents', 'ComponentController@getComponentIncidents');
// Incidents
Route::get('incidents', 'IncidentController@getIncidents');

View File

@@ -53,18 +53,6 @@ class ComponentController extends Controller
return $this->component->findOrFail($id);
}
/**
* Return a component with incidents.
*
* @param int $id
*
* @return \CachetHQ\Cachet\Models\Component
*/
public function getComponentIncidents($id)
{
return $this->component->with($id, ['incidents']);
}
/**
* Create a new component.
*

View File

@@ -7,6 +7,16 @@ use League\Fractal\TransformerAbstract;
class ComponentTransformer extends TransformerAbstract
{
/**
* List of resources possible to include.
*
* @var array
*/
protected $availableIncludes = [
'incidents',
'tags',
];
/**
* Transform a component model into an array.
*
@@ -27,4 +37,28 @@ class ComponentTransformer extends TransformerAbstract
'updated_at' => $component->updated_at->timestamp,
];
}
/**
* Include component incidents.
*
* @return League\Fractal\Resource\Collection
*/
public function includeIncidents(Component $component)
{
$incidents = $component->incidents;
return $this->collection($incidents, new IncidentTransformer());
}
/**
* Include components tags.
*
* @return League\Fractal\Resource\Collection
*/
public function includeTags(Component $component)
{
$incidents = $component->tags;
return $this->collection($incidents, new TagTransformer());
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace CachetHQ\Cachet\Transformers;
use CachetHQ\Cachet\Models\Tag;
use League\Fractal\TransformerAbstract;
class TagTransformer extends TransformerAbstract
{
/**
* Transform a tag model into an array.
*
* @param \CachetHQ\Cachet\Models\Tag $tag
*
* @return array
*/
public function transform(Tag $tag)
{
return [
'id' => (int) $tag->id,
'name' => $tag->name,
'description' => $tag->slug,
'created_at' => $tag->created_at->timestamp,
'updated_at' => $tag->updated_at->timestamp,
];
}
}