Reputation: 4152
I have something like the following table (tablename = applications
):
| id | applicants |
| ------------- | ------------- |
| uuid-123-abc | [{'first_name':'Dave'},{'first_name':'Steve'}] |
I need to be able to create a relationship for it so I can just go:
$application->applicants
and (in this example) get a collection with two Applicant
models.
I'm assuming I'll need an Applicant model class somewhere. But I'm not even sure if this can be done because there is no applicant
table.
I was trying just:
public function applicants()
{
return Collection::make([$this->applicants]);
But that's not a relationship and I'm trying to get this to work with Neromerx JsonApi.
In fact, if there is a way to imitate this behaviour for JsonApi I'd just as happily use that solution.
So far my relationships have all been pretty straight forward. And I'd like to be able to get the applicants in the same way:
use Neomerx\JsonApi\Schema\SchemaProvider;
class ApplicationSchema extends SchemaProvider
{
protected $resourceType = 'applications';
public function getId($application) {
return $application->id;
}
public function getAttributes($application) {
return [
.....
];
}
public function getRelationships($application, $isPrimary, array $includeRelationships) {
return [
'applicants' => [self::DATA => $application->applicants];
];
}
}
Can it be done using one of these approaches?
I'm not using Laravel I'm just using Eloquent (version 5.5) on it's own in Slim.
Upvotes: 0
Views: 596
Reputation: 25926
Try this:
public function getApplicantsAttribute()
{
$items = json_decode($this->attributes['applicants']);
$instance = new Applicant();
return $instance->newCollection(array_map(function($item) use($instance) {
return $instance->newFromBuilder($item);
}, $items));
}
Upvotes: 0