渴望加载深层嵌套的关系?
作者:互联网
我有一系列与此相关的表格;
trainers -> hasMany -> programs
programs -> hasMany -> weeks
weeks -> hasMany -> days
days -> hasMany -> sessions
sessions -> hasMany -> phases
phases -> hasMany -> excersises
相反方向的关系都对运动阶段有一个接受,这也有很多
按照文档将这种关系深化很显然很正常
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days')->get();
我需要能够检索整个程序的内容,并且我认为我可以急于加载每个嵌套关系,如下所示:
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days', 'weeks.days.sessions')->get();
要么
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->with('weeks.days.sessions')->get();
但都返回FatalErrorException
Call to undefined method
Illuminate\Support\Facades\Session::newQuery()
正确的方法是什么?
解决方法:
从您的问题中,我可以看到您具有如下的嵌套关系.
programs -> hasMany -> weeks
-----------------------------weeks -> hasMany -> days
----------------------------------------------------days -> hasMany -> sessions
如果我们不知道几周,那么很难知道几天应该加载什么数据.对于会话也是如此.因此,我们必须先加载星期数据,然后再加载几天,然后再加载会话.
从Laravel文档中,我们可以看到,使用以下方法渴望加载:
select * from books
select * from authors where id in (1, 2, 3, 4, 5, ...)
Laravel根据书籍数据加载作者数据.
http://laravel.com/docs/eloquent#eager-loading
尝试先加载几周
$programs = $this->program->orderBy('trainerId', 'asc')
->take(1)
->with('weeks', 'weeks.days', 'weeks.days.sessions')
->get();
要么:
懒惰渴望加载:
$programs = $this->program->orderBy('trainerId', 'asc')->take(1)->get();
$programs->load('weeks', 'weeks.days', 'weeks.days.sessions');
标签:eloquent,laravel-4,mysql,php,database 来源: https://codeday.me/bug/20191122/2058461.html