【发布时间】:2019-06-10 02:38:13
【问题描述】:
我想显示一个教室的所有可用时间(每天 9 小时),包括该小时的容量和该小时允许的部门,包括被排除在教室之外的科目或教室所在的科目独家的。 在我的 show.blade.php 中,我构建了一个表格,每个表格单元显示一个可用小时。由于这需要两个循环,一个用于一天中的一个循环,一个用于一天中的一个小时,我想急切地在课堂上加载这些关系。但从完成请求所需的时间(几乎 2 秒)和望远镜报告的查询数量来看,无论是否预先加载,都会对数据库提出质疑。
在我的控制器中,我加载这样的关系:
$classroom->load('availableHours.allowedDepartments.exclusiveSubjects.subject',
'availableHours.allowedDepartments.excludedSubjects.subject',
'availableHours.allowedDepartments.department');
如果我转储教室,则会加载关系。在我的 show.blade.php 中,我像这样遍历 availableHours:
<!-- loop through all the hours of the day -->
@for($i=1;$i<=$maxHour;$i++)
<tr>
<td>
<a href="/classrooms/{{$classroom->number}}/0/{{$i}}/edit">
{{$i}}
</a></td>
<!-- loop through all the days -->
@foreach($days as $day)
<!-- show the available hour either in green (available) or red (unavailable)-->
<td>
<a href="/classrooms/{{$classroom->number}}/{{$day->id}}/{{$i}}/edit">
<!-- show the capacity of the hour of the day-->
{{ $classroom->availableHours()->where([['day_id','=',$day->id],['hour_of_day',$i]] )->first()->capacity }} <br/>
@foreach($classroom->availableHours()->where([['day_id','=',$day->id],['hour_of_day',$i]] )->first()->allowedDepartments as $allowedDepartment)
<!-- show the permitted departments along with any exclusive or excluded subjects-->
{{$allowedDepartment->department->name}}
@foreach ($allowedDepartment->exclusiveSubjects as $subjectDepartment)
{{$subjectDepartment->subject->code}}
@endforeach
<br/>
@endforeach
</a></td>
@endforeach
</tr>
@endfor
正如我所说,这会导致再次查询数据库,而不是使用预加载的关系。我做错了什么?
【问题讨论】:
标签: laravel eager-loading