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
相关产品推荐
相关产品推荐

