Laravel Api 资源

Laravel Api Resource

我正在尝试使用 Laravel 的资源为我的数据表创建一个 API。我有三个具有关系的模型。每次我点击 api 路由来检查结果时,我都会在 sub_specializations 中得到一个空值。这是已经 JSON 格式化的结果。

    { 
"data":[ 
    { 
        "first_name":"Rusty",
        "last_name":"Ferry",
        "specializations":{ 
            "specialization_id":11,
            "specialization_name":"Endocrinology"
        },
        "sub_specializations":null
    },
    { 
        "first_name":"Nadia",
        "last_name":"Ondricka",
        "specializations":{ 
            "specialization_id":22,
            "specialization_name":"ENT"
        },
        "sub_specializations":null
    },
    { 
        "first_name":"Erich",
        "last_name":"Torphy",
        "specializations":{ 
            "specialization_id":2,
            "specialization_name":"Cardiologist"
        },
        "sub_specializations":null
    }
    ]
}

这是我所有的资源。这是 DoctorsResource

    public function toArray($request)
{
    return [
        'first_name' => $this->first_name,
        'last_name'  => $this->last_name,
        'specializations' => new SpecializationsResource($this->specializations),
        'sub_specializations' => new SubSpecializationsResource($this->sub_specializations),
    ];
}

专业资源

    public function toArray($request)
{
    return [
        'specialization_id' => $this->specialization_id,
        'specialization_name' => $this->specialization_name,
    ];

}

子专业

    public function toArray($request)
{
    return [
        'sub_specialization_id' => $this->sub_specialization_id,
        'sub_specialization_name' => $this->sub_specialization_name,
        'doctors' => new DoctorsResource($this->doctors),
    ];
}

最后,这是控制器

    protected $user;

public function __construct(Doctors $doctors){
    $this->doctors = $doctors;
}

public function index()
{
    $doctors = $this->doctors->with('specializations', 'subSpecializations')->get();
    return DoctorsResource::collection($doctors);
}

我期待的结果与此类似

{ 
"data":[ 
    { 
        "first_name":"Rusty",
        "last_name":"Ferry",
        "specializations":{ 
            "specialization_id":11,
            "specialization_name":"Endocrinology"
        },
        "sub_specializations": {
            "sub_specialization_name":"value"
       }
    }
  ]
}

您必须确保有特定医生的子专科数据。

如果有数据则将该数据添加到医生资源中,否则它将是空白的。

只需要在医生资源中更改行,例如:

'sub_specializations' => $this->sub_specializations !== null ? new SubSpecializationsResource($this->sub_specializations) : '',

您也可以使用 专业 做同样的事情。