【问题标题】:How do I create relationship from json column data on same table?如何从同一张表上的 json 列数据创建关系?
【发布时间】:2018-05-02 17:20:39
【问题描述】:

我有类似下表的内容 (tablename = applications):

| id            | applicants    |  
| ------------- | ------------- | 
| uuid-123-abc  | [{'first_name':'Dave'},{'first_name':'Steve'}] | 

我需要能够为它建立关系,这样我就可以走了:

$application->applicants 和(在本例中)获取包含两个 Applicant 模型的集合。

我假设我在某处需要一个申请人模型类。但是我什至不确定是否可以这样做,因为没有applicant 表。

我只是在尝试:

public function applicants()
{
    return Collection::make([$this->applicants]);

但这不是一种关系,我正试图让它与Neromerx JsonApi一起工作。

事实上,如果有一种方法可以为 JsonApi 模仿这种行为,我会很乐意使用该解决方案。

到目前为止,我的人际关系都非常简单。而且我希望能够以同样的方式获得申请人:

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

可以使用其中一种方法来完成吗?

我没有使用 Laravel,我只是在 Slim 中使用 Eloquent(5.5 版)。

【问题讨论】:

  • 这种“关系”应该具备哪些特点?您是否只想从 JSON 字符串中获取 Applicant 实例的集合?
  • 这应该就是所有需要的了,是的。它应该在 Eloquent 模型的“关系”范围内可用。
  • 最后一句到底是什么意思?
  • Eloquent 模型有一个“relations”属性,它将包含所有现有的(如果需要的话)相关数据。 Here be the docs
  • 为什么在您的案例中使用$relations 属性很重要?

标签: eloquent json-api


【解决方案1】:

试试这个:

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

【讨论】:

  • 但我仍然无法通过 Application 模型将其作为关系加载。例如$application->applicants
  • 您可以,如果您将方法重命名为getApplicantsAttribute 并将$this->applicants 替换为$this->attributes['applicants']
猜你喜欢
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多