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

Laravel API Resource:如何在whenLoaded关联中加载嵌套关联?

解决Laravel Resource嵌套关联加载问题

嘿,这个问题我之前也碰到过!核心原因是你虽然在Yard Resource里加载了latestInspection,但它的嵌套关联tasks和feeds并没有被预加载或加载,导致Inspection Resource里的whenLoaded条件不满足,所以这些字段不会被输出。下面给你两种靠谱的解决方案:

方案一:查询时预加载嵌套关联

如果你确定每次获取Yard数据时都需要这些嵌套关联,最推荐的方式是在查询Yard的时候直接预加载所有需要的层级关联。这样能避免N+1查询问题,性能更好:

// 在你的控制器或查询逻辑中
$yards = Yard::with([
    'latestInspection',
    'latestInspection.tasks',
    'latestInspection.feeds'
])->get();

这样当Yard模型被加载时,latestInspection以及它的tasks、feeds关联都会被一次性预加载,Inspection Resource里的whenLoaded('tasks')和whenLoaded('feeds')就会触发,输出对应的字段。

方案二:在Resource中动态加载缺失的关联

如果你的场景更灵活,有时候只需要加载latestInspection而不需要嵌套关联,或者不确定查询时有没有预加载,可以在Yard Resource里处理latestInspection的时候,手动加载缺失的嵌套关联:

// Yard Resource中修改latest_inspection字段的定义
'latest_inspection' => $this->whenLoaded('latestInspection', function () {
    // 加载latestInspection中未被预加载的tasks和feeds关联
    $this->latestInspection->loadMissing(['tasks', 'feeds']);
    return new InspectionResource($this->latestInspection);
})

loadMissing方法只会在关联还没被加载的时候才执行查询,不会重复加载,兼顾了灵活性和性能。

额外检查点

别忘了确保你的Inspection模型里已经正确定义了这两个关联:

// app/Models/Inspection.php
public function tasks()
{
    return $this->hasMany(Task::class); // 根据你的实际关联类型调整
}

public function feeds()
{
    return $this->hasMany(Feed::class); // 根据你的实际关联类型调整
}

这样调整之后,你就能在Yard Resource的latest_inspection字段里看到Inspection Resource中定义的completed_tasks和feedings数据啦!

内容的提问来源于stack exchange,提问作者Pedro

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:14:35