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

Laravel Eloquent三级嵌套关联:同时加载Nomenclature的多关联模型

解决Laravel三级关联嵌套加载多个关联的问题

嗨,这个场景Laravel的预加载机制完全能搞定!你只需要调整下with方法的参数,就能同时把uom和ingredients都挂载到nomenclature对象上,有两种实用写法可选:

方法一:简洁的点语法嵌套

和你之前加载uom的逻辑一致,直接通过点语法把nomenclature的两个关联都列出来就行,适合不需要额外筛选条件的场景:

$plan = Plan::with([
    'steps',
    'items.nomenclature.uom',
    'items.nomenclature.ingredients'
])->find($yourPlanId);

这样加载完成后,你遍历$plan->items时,每个item下的nomenclature都会同时包含一对一的uom对象和一对多的ingredients集合。

方法二:闭包控制加载逻辑(支持自定义条件)

如果后续需要对uom或ingredients加查询条件(比如只加载状态活跃的配料),用闭包嵌套的方式灵活性更高:

$plan = Plan::with([
    'steps',
    'items.nomenclature' => function ($query) {
        $query->with([
            'uom',
            'ingredients' => function ($ingredientQuery) {
                // 这里可以添加自定义筛选条件,比如只加载活跃配料
                $ingredientQuery->where('is_active', true);
            }
        ]);
    }
])->find($yourPlanId);

两种写法都能满足你的需求,核心就是在预加载nomenclature时,把它的两个关联关系都纳入加载范围就好啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:07:46