【问题标题】:Eloquent ID & Foreign keyEloquent ID 和外键
【发布时间】:2020-02-16 22:39:23
【问题描述】:

我的表 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>

我不明白我的问题。

我提前感谢您的帮助。

【问题讨论】:

  • 我更新了您的问题并修改了您提到的模型(从:“在我的Retour 模型中我有这个”到:“在我的Cous 模型中我有这个”)。如果这不正确,请修改它。

标签: php laravel laravel-5 eloquent relationship


【解决方案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

如果您仅从刀片页面上的第一个循环分解此内容,则您将从retour 对象的整体集合中的第一个retour 对象中提取第一个eleves。然后,您将从第一个 eleves 中的第一个 cours 对象中拉出第一个 retour 对象。日期相同的原因是您可能在提取相同的cours 对象。我说可能是因为first() 方法只是拉取与数据库中retour 对象关联的第一个实例。不是最新的,只是第一个。所以,如果每个retour 有多个eleves,如果说id 为1 的那个同时连接到第一个和第二个retour,那么你在第二个eleves环形。在 courseleves 的关系上完全相同的问题进一步加剧了这种情况。如果您说coursid(共21 个)附加到多个eleves,您可能会拉出完全相同的cours,即使您处于两个@ 完全不同的循环中987654347@和eleves

要解决此问题,您需要在循环中引用的 which eleveswhich 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 对象)。

【讨论】:

  • 非常感谢 Watercayman 的解释和花时间给我写信。我会改变它并按照你的步骤。:-)
猜你喜欢
  • 2018-04-13
  • 2017-05-28
  • 2018-10-21
  • 2015-05-21
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
  • 2018-08-24
  • 2020-03-28
相关资源
最近更新 更多