Laravel API 资源

Posted

技术标签:

【中文标题】Laravel API 资源【英文标题】:Laravel Api Resource 【发布时间】:2020-03-23 15:55:26 【问题描述】:

我正在尝试使用 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"
       
    
  ]

【问题讨论】:

【参考方案1】:

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

如果有数据,则将该数据添加到 Doctor Resource,否则它将为空白。

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

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

你也可以用专业化做同样的事情。

【讨论】:

谢谢兄弟,抱歉回复晚了。这帮助我解决了我的问题

以上是关于Laravel API 资源的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.6 API 资源未显示关系数据

Laravel API 资源

用于 API 和非 API 的 Laravel 资源控制器

Laravel - 如何递归地将 API 资源转换为数组?

Laravel 返回自定义 api 资源

Laravel API 资源中的多级关系