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
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
leo
最佳答案

with(['studentInfo.recommendPerson'])

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

with(['studentInfo.recommendPerson'])

7年前 评论
leo

with(['studentInfo.recommendPerson'])

7年前 评论
bestony

@leo 感谢!可行。

7年前 评论

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