You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中Resource使用whenLoaded加载hasManyThrough关联返回空问题

问题成因

  1. 关联调用逻辑错误:你在Component模型上预加载的fields关联对应返回的是Field模型集合,传入FieldResource后,当前FieldResource对应的数据源是单个Field模型实例,而Field模型本身并没有定义名为fields的关联,你在FieldResource中调用$this->whenLoaded('fields')必然返回空值。
  2. 资源嵌套逻辑混乱:你在FieldResource中又实例化了ComponentValueResource,形成了循环嵌套的错误逻辑,完全背离了两类资源的设计用途。
  3. 你dd时看到的是未经过toArray处理的资源原始数据,实际接口返回时会执行toArray方法的错误逻辑,因此最终输出为空。

解决方法

  1. 修正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模型字段
    ];
}
  1. 完善ComponentValueResource的字段定义,补充需要返回的Component模型自身属性:
public function toArray($request)
{
    return [
        'id' => $this->id,
        // 按需添加其他需要返回的Component模型字段
        'fields' => FieldResource::collection($this->whenLoaded('fields')),
    ];
}

修改后再次请求接口即可正常返回关联的fields数据。

内容的提问来源于stack exchange,提问作者Jesse de Boer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:15:02