How do I create relationship from json column data on same table?

戏子无情 提交于 2019-12-24 23:33:06

问题


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.


回答1:


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));
}


来源:https://stackoverflow.com/questions/50140271/how-do-i-create-relationship-from-json-column-data-on-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!