首页 > 解决方案 > Eloquent ID & Foreign key

问题描述

My table Cous has a column date_seance with 2 recordings.

enter image description here

In my table Retour, I have to retrieve the date_seance.

enter image description here

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.

标签: phplaravellaravel-5eloquentrelationship

解决方案


有几件事要提。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 ,那么你拉的是相同的retourretourcourselevesretourcoursfirst()retourelevesretouridretoureleves在第二个循环中。cours与 的关系完全相同的问题进一步加剧了这种情况eleves。如果您说 a courswith idof 21 附加到多个eleves,即使您处于完全不同的循环中,您也可能会拉出完全相同的和。coursretoureleves

要解决此问题,您需要对循环中引用的对象和对象 eleves一个可靠的处理。 cours我建议不要在顶层 ( retours) 进行查询,而是对这些关系 (elevescours) 进行几个较低级别的查询,然后直接在刀片中的那些上进行循环。

例如在你的控制器中

$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对象)。


推荐阅读