【问题标题】:How to load relations with { json:api } Client?如何加载与 { json:api } 客户端的关系?
【发布时间】:2019-11-28 18:05:06
【问题描述】:

我正在使用 {json:api} Client 将 json 解析为 Eloquent 类模型。

我有两个模型,CongressSpeaker。一个Congress 有很多Speaker

这是我能够做到的:

$repository = app(App\Repositories\CongressRepository::class);
$document = $repository->all();

$document 是具有以下属性的CollectionDocument

我想获得第一个Congressspeakers。这是我尝试过的

$congresses = $document->getData();
$congress = $congresses->first();
$congress->speakers // <- this is null!

为什么$congress-&gt;speakers 为空?我也试过给我们$repository-&gt;all(['includes' =&gt; 'speakers']); 但这没有区别。

【问题讨论】:

    标签: laravel json-api


    【解决方案1】:

    似乎$congress-&gt;speakers 为空,因为关系为空:

    我使用this 包来创建json 输出。在Schema.php 中,我必须添加self::DATA 以使数据可见,如docs 中所述。

    public function getRelationships($resource, $isPrimary, array $includeRelationships)
    {
        return [
            'speakers' => [
                self::SHOW_SELF => true,
                self::SHOW_RELATED => true,
                self::DATA => function () use ($resource) {
                    return $resource->speakers;
                },
            ],
        ];
    }
    

    我仍然想知道是否可以加载关系,如果在API 中只给出link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2020-04-13
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      相关资源
      最近更新 更多