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

Laravel中如何在with('position')中嵌套with('role')获取关联数据

解决方案:嵌套加载关联模型

你只需要在with()方法中使用点语法指定嵌套关联,就能同时加载position及其关联的role数据。

修改后的代码如下:

public function getTheUser()
{
    return User::where('user_id', '10')
            ->with('position.role') // 用点语法嵌套加载role关联
            ->get();
}

原理说明

Laravel Eloquent支持通过.链式指定嵌套关联关系,with('position.role')会先加载用户的position关联,再自动加载该职位对应的role关联,最终返回的JSON数据会包含你预期的role层级结构。

验证结果

执行修改后的代码后,API返回结果将与你预期的结构一致:

[
    {
        "id": 10,
        "name": "Mary",
        "gender": "Female",
        "position": {
            "id": 1,
            "position": "Executive",
            "role": {
                "id": 1,
                "role": "Manager"
            }
        }
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:45:33