首页 > 解决方案 > Laravel 资源 whenLoaded hasManyTrough 关系

问题描述

我正在尝试使用基于 hasManyThrough 关系的第二个资源来构建资源集合。当我调用主要资源上的实际关系时,它确实为我提供了正确的数据。每当我将数据传递给另一个资源并使用 whenLoaded() 方法时,它不会将数据链接到主集合。

该模型:

public function fields()
{
    return $this->hasManyThrough(Field::class, FieldValue::class, 'component_id', 'id', 'id', 'field_id');
}

控制器:

/**
 * @return JsonResponse
 */
public function index()
{
    $components = Component::with(['fields'])->get();

    return ComponentValueResource::collection($components)->response();
}

组件值资源类:

public function toArray($request)
{
    return [
        'fields' => FieldResource::collection($this->whenLoaded('fields')),
    ];
}

字段资源类:

public function toArray($request)
{

    $fields = $this->whenLoaded('fields');
    return [
        'fields' => new ComponentValueResource($fields),
    ];
}

的输出dd(FieldResource::collection($this->whenLoaded('fields')));

#original: array:9 [
        "id" => 1
        "base_id" => 1
        "component_id" => null
        "identifier" => "text input"
        "type" => "text"
        "position" => 1
        "created_at" => "2021-08-22 19:44:23"
        "updated_at" => "2021-08-22 19:44:23"
        "laravel_through_key" => 6
      ]

资源的输出:

{
"data": [
    {
        "id": 6,
        "fields": [
            []
        ]
    },

标签: phplaravelapieloquenteloquent-relationship

解决方案


推荐阅读