【问题标题】:How laravel assign this to the model given in resourceslaravel 如何将其分配给资源中给出的模型
【发布时间】:2019-10-01 10:04:16
【问题描述】:

Laravel 如何将 $this 重新分配给 Api 资源中给出的模型,并在技术上返回类中的 just 方法?

假设我们有这个:

new TeamResource(Team::first());

那么,当我们调用$this 时,在TeamResrouce 中,它的Team 模型实例。

并自动调用TeamResource 类中的toArray() 方法。

在确切的类中没有任何构造函数,怎么办?

【问题讨论】:

  • this 在哪里?你是说$this 吗?
  • 是的,我的意思是这个

标签: php laravel api class controller


【解决方案1】:

toArray() 调用作为模型实例的 toJson() 调用是在 laravel 内核和请求管道中完成的。这是一些代码

Illuminate\Routing\Router@toResponse()

 public static function toResponse($request, $response)
    {
        if ($response instanceof Responsable) {
            $response = $response->toResponse($request);
        }

        if ($response instanceof PsrResponseInterface) {
            $response = (new HttpFoundationFactory)->createResponse($response);
        } elseif ($response instanceof Model && $response->wasRecentlyCreated) {
            $response = new JsonResponse($response, 201);
        } elseif (! $response instanceof SymfonyResponse &&
                   ($response instanceof Arrayable ||
                    $response instanceof Jsonable ||
                    $response instanceof ArrayObject ||
                    $response instanceof JsonSerializable ||
                    is_array($response))) {
            $response = new JsonResponse($response);
        } elseif (! $response instanceof SymfonyResponse) {
            $response = new Response($response);
        }

        if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
            $response->setNotModified();
        }

        return $response->prepare($request);
    }

【讨论】:

    【解决方案2】:

    魔法法(__get):

    public function __get($key)
    {
        return $this->resource->{$key};
    }
    

    API 资源 (Illuminate\Http\Resources\Json\JsonResource) 定义了此方法,因此您可以通过访问资源本身的属性来访问底层模型的属性。

    $this->something === $this->resource->something;
    

    请注意,我们可以直接从 $this 变量访问模型属性。这是因为资源类会自动将属性和方法访问代理到底层模型以方便访问。 Laravel 5.8 Docs - Eloquent - API Resources

    【讨论】:

    • 没关系,但是 laravel 在 make new TeamResource() 时如何调用 toArray() func ?
    • 当您创建TeamResource 的新实例时它不会调用toArray,它会在稍后解决,很可能根据N69S 的答案JsonResourceJsonSerializable
    【解决方案3】:

    我看到了两种可能的情况,一种是我还没有真正看到有人使用另一个类模型来初始化一个完全不同的类。您的问题可能出在您初始化的那种方式上。

    你也可以尝试分配$this = TeamsResource(Team::first())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      相关资源
      最近更新 更多