【问题标题】:Laravel / League Fractal returns an empty array instead of empty objectLaravel / League Fractal 返回一个空数组而不是空对象
【发布时间】:2019-06-05 21:16:06
【问题描述】:

我在使用 Fractal 库时遇到问题。我正在使用 Spatie\laravel-fractal 库,它只是 League\fractal 的包装器。所以...

我想返回一个空对象而不是一个空数组。

public function includeDocumentType(Question $question)
{
    return $question->documentType
        ? $this->item($question->documentType, new DocumentTypeTransformer)
        : $this->null();
}

$this->null() 在生成后总是返回[],我想返回{}。 Tbh 我想要 2 个函数,例如 $this->nullItem()$this->nullCollection()

有谁知道这个问题的解决方法是什么?

【问题讨论】:

  • 你可以只返回 new stdClass() 而不是 $this->null()(对于空对象)
  • @ljubadr 它不起作用,因为这个函数预计会返回League\Fractal\Resource\ResourceInterface
  • $this->item(null, new DocumentTypeTransformer) 工作吗?
  • @ceejayoz 问题是new NullResource() 总是被转换成一个数组。我在他们的库 GitHub 页面上创建了一个问题。希望他们能解决它。

标签: php laravel laravel-5 thephpleague-fractal


【解决方案1】:

我刚刚遇到了同样的问题。我想返回空数组而不是NullResource。这是我从源代码中找到的。

而不是$this->null()$this->primitive(null) 成功了。您可以输入任何您想要返回的内容。

在你的情况下$this->primitive(new \stdClass()) 应该是要走的路。

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2016-06-27
    • 2020-04-08
    • 2013-07-22
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    相关资源
    最近更新 更多