我的表Cous
的列date_seance
中有2条录音。
在我的表Retour
中,我必须检索date_seance
。
除此以外,我总是检索相同的值。
23/10/2019
在哪里?
在我的模型Cous
中,我有这个:
public function retours()
{
return $this->hasManyThrough(
'App\Retour',
'App\Eleve',
'fk_cours',
'fk_eleve',
'id',
'id'
);
}
在我的Retour
index.blade.php
中,我有这个:
@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>
我的问题是这一行:
<td> {{ $retour->eleves()->first()->cours()->first()->date_seance->format('d/m/Y') }}</td>
我不明白我的问题。
在此先感谢您的帮助。
答案 0 :(得分:1)
几件事要提。首先,按如下所示在您的刀片式服务器上调用您的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
对象集合中的第一个retour
对象中提取第一个retour
。然后,您将从第一个cours
对象的第一个eleves
对象中拉出第一个retour
对象。日期相同的原因是可能拉相同的cours
对象。我说这可能是因为first()
方法只是拉出与数据库中的retour
对象关联的第一个实例。不是 latest ,而是第一个。因此,如果每个eleves
有多个retour
,则第一个id
和第二个retour
都附有eleves
为1的那个。在第二个循环中使用完全相同的cours
。与eleves
的{{1}}关系完全相同的问题进一步加剧了这一问题。如果您说一个cours
,其中id
中有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
对象)。