php - Eloquent ID & Foreign key
问题描述
My table Cous
has a column date_seance
with 2 recordings.
In my table Retour
, I have to retrieve the date_seance
.
Except that, I always retrieve the same value.
Where is the 23/10/2019
one?
In my model Cous
I have this:
public function retours()
{
return $this->hasManyThrough(
'App\Retour',
'App\Eleve',
'fk_cours',
'fk_eleve',
'id',
'id'
);
}
In my Retour
index.blade.php
I have this:
@foreach($retours as $retour)
<tr>
<td> {{$retour->instruction}}</td>
<td> {{$retour->description}}</td>
<td> {{$retour->eleves->nom}}</td>
<td> {{$retour->eleves->prenom}}</td>
<td> {{$retour->eleves()->first()->cours()->first()->date_seance->format('d/m/Y')}}</td>
<td> {{$retour->eleves()->first()->cours()->first()->moniteurs->nom}}</td>
<td> {{$retour->eleves()->first()->cours()->first()->moniteurs->prenom}}</td>
<td> {{$retour->eleves()->first()->paiements()->first()->date_saisie->format('d/m/Y')}}</td>
My problem is this line:
<td> {{ $retour->eleves()->first()->cours()->first()->date_seance->format('d/m/Y') }}</td>
I don't understand my problem.
I thank you in advance for your help.
解决方案
有几件事要提。eleves
首先,在刀片表单上调用您的关系,如下所示:
$retour->eleves()
每次调用都会返回数据库。retour
如果您有很多对象,或者即使您只是通过该表,这可能会增加很多延迟。
retour
强烈建议至少在集合 上尽可能多地预先加载。
在您的控制器上:
// Not sure if you had any constraints, but this will eager load eleves
$retours = Retour::with('eleves')->get();
您总是拉同一个日期的问题是您可能从同一个对象中拉出。我喜欢一条好的链条……但有时更长的链条变得比它们的价值更令人困惑。看看这一行:
$retour->eleves()->first()->cours()->first()->date_seance
如果您仅从刀片页面上的第一个循环分解此循环,则您将从整个对象集合中的eleves
第一个对象中提取第一个循环。然后,您从第一个对象中拉出第一个对象。日期相同的原因是您可能正在拉同一个对象。我说可能是因为该方法只是拉取与数据库中的对象关联的第一个实例。不是最新的,只是第一个。因此,如果every有多个,如果 say为 1 的那个同时连接到 first 和 second ,那么你拉的是相同的retour
retour
cours
eleves
retour
cours
first()
retour
eleves
retour
id
retour
eleves
在第二个循环中。cours
与 的关系完全相同的问题进一步加剧了这种情况eleves
。如果您说 a cours
with id
of 21 附加到多个eleves
,即使您处于完全不同的循环中,您也可能会拉出完全相同的和。cours
retour
eleves
要解决此问题,您需要对循环中引用的对象和对象有 eleves
一个可靠的处理。 cours
我建议不要在顶层 ( retours
) 进行查询,而是对这些关系 (eleves
或cours
) 进行几个较低级别的查询,然后直接在刀片中的那些上进行循环。
例如在你的控制器中:
$courses = Cours::where('some constraint', $someConstrainer)->get()
然后,在您的刀片中,只需循环$courses
收集:
@foreach($courses as $cours){
// Other stuff here...
<td> {{ $cours->first()->date_seance->format('d/m/Y') }}</td>
如果您无法在该cours
级别执行此操作,则可能会退出更高级别并加载eleves
(同时急切加载cours
对象)。
推荐阅读
- react-native - React Native:如何在 react native v5(不是 v4)中将多个 stackNavigator 包含到一个 DrawerNavigator 中
- reactjs - CDataTable (Core UI React) prop onPageChange 触发 2 次
- image - 网站更新清除所有客户端设备上的缓存,以便更新图像和内容
- r - 一个矩阵的行名和列名到另一个矩阵
- angular - 如何使用角度中的elementRef在一个分区中搜索选定的复选框
- javascript - React Material UI OutlinedInput 不显示错误信息
- mysql - 从当前行和上一行计算 2 列
- python - 如何使用赋值表达式和打字?
- docker - 在 Docker 映像上安装 SSH
- javascript - 如何将“日期”类型的输入值传递给每秒计算和更新年龄的函数