Eloquent Model 如何实现多层的 with 方法?
需求描述:多层关系获取如何使用with来预加载。
在属于一对多关系时。经常会用到with来预加载数据,加快速度。
但是如果连续两层使用关系,该如何在第二层上加载with呢?
表1 为订单表,其中有字段student_id,关联到了student表
表2为学员表,其中有字段 recommend_person,关联到了user表。
表3为用户表,字段有name
具体需求:
在对订单表进行get获取时,会使用with来加载数据,但是在debugBar中依然有较多的查询,
我希望通过再次使用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');
}
推荐文章: