我正在尝试使用 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 } ]}这是我所有的资源。这是医生资源 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);}
1 回答
ITMISS
TA贡献1871条经验 获得超8个赞
您必须确保有特定医生的子专业数据。
如果有数据,则将该数据添加到 Doctor Resource,否则将为空白。
只需要更改医生资源中的行,例如:
'sub_specializations' => $this->sub_specializations !== null ? new SubSpecializationsResource($this->sub_specializations) : '',
你也可以用专业做同样的事情。
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报
0/150
提交
取消