Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

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

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 NeomerxJsonApiSchemaSchemaProvider;

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...