Eloquent Model 如何实现多层的 with 方法?

需求描述:多层关系获取如何使用with来预加载。

在属于一对多关系时。经常会用到with来预加载数据,加快速度。
但是如果连续两层使用关系,该如何在第二层上加载with呢?

表1 为订单表,其中有字段student_id,关联到了student表
表2为学员表,其中有字段 recommend_person,关联到了user表。
表3为用户表,字段有name

具体需求:
在对订单表进行get获取时,会使用with来加载数据,但是在debugBar中依然有较多的查询,
file
我希望通过再次使用with来预加载这里的user信息。

相关代码
表1Get方法

 $data = Order::where("order_type", 'entry')->with('studentInfo')->get();
 return view('order.list', ['data' => $data]);

表1的studentinfo

 public function studentInfo(){
        return $this->belongsTo('App\Student','user_id','id');
    }

表2的recommend_person

          public function recommendPerson(){
        return $this->belongsTo('App\User','recommended_person','id');
    }
bestony
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
leo
最佳答案

with(['studentInfo.recommendPerson'])

7年前 评论
讨论数量: 2
leo

with(['studentInfo.recommendPerson'])

7年前 评论
leo

with(['studentInfo.recommendPerson'])

7年前 评论
bestony

@leo 感谢!可行。

7年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!