Laravel中Resource使用whenLoaded加载hasManyThrough关联返回空问题
问题成因
- 关联调用逻辑错误:你在
Component模型上预加载的fields关联对应返回的是Field模型集合,传入FieldResource后,当前FieldResource对应的数据源是单个Field模型实例,而Field模型本身并没有定义名为fields的关联,你在FieldResource中调用$this->whenLoaded('fields')必然返回空值。 - 资源嵌套逻辑混乱:你在
FieldResource中又实例化了ComponentValueResource,形成了循环嵌套的错误逻辑,完全背离了两类资源的设计用途。 - 你
dd时看到的是未经过toArray处理的资源原始数据,实际接口返回时会执行toArray方法的错误逻辑,因此最终输出为空。
解决方法
- 修正
FieldResource的代码,直接返回Field模型自身的属性即可,不需要调用不存在的关联,也不需要嵌套ComponentValueResource:
public function toArray($request) { return [ 'id' => $this->id, 'base_id' => $this->base_id, 'identifier' => $this->identifier, 'type' => $this->type, 'position' => $this->position, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, // 按需添加其他需要返回的Field模型字段 ]; }
- 完善
ComponentValueResource的字段定义,补充需要返回的Component模型自身属性:
public function toArray($request) { return [ 'id' => $this->id, // 按需添加其他需要返回的Component模型字段 'fields' => FieldResource::collection($this->whenLoaded('fields')), ]; }
修改后再次请求接口即可正常返回关联的fields数据。
内容的提问来源于stack exchange,提问作者Jesse de Boer
相关产品推荐
相关产品推荐

