【问题标题】:Laravel - Element displaying twice while looping inside a conditionLaravel - 在条件内循环时元素显示两次
【发布时间】:2021-11-23 02:15:12
【问题描述】:
This is the example while looping
尽管有太多的条件和关系,但似乎情况
@foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)
@if (\App\Document::where('id',$item->id_document)->get())
<a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download" > Telecharger </a>
@endif
@endforeach
【问题讨论】:
标签:
laravel
if-statement
laravel-5
eloquent
while-loop
【解决方案1】:
首先你不应该在刀片文件中加载数据
在控制器功能内执行
那么您应该在 ClientDocument 模型名称文档中创建关系
在你的刀片中你可以做到这一点
$项目->文档
或任何你想要的
【解决方案2】:
在上面的sn-p中
@foreach (\App\ClientDocument::where('id_client', $clients->id)->get() as $item)
@if (\App\Document::where('id',$item->id_document)->get())
<a class="img-fluid " href="{{asset('images/'.$item->file)}}" download="{{asset('images/'.$item->file)}}" alt="" name="download" > Telecharger </a>
@endif
@endforeach
代码绝对没问题,但也有可能,您正在使用重复数据运行,您也可以使用它。
\App\ClientDocument::where('id_client', $clients->id)->distinct('id_client')->get()
而不是使用@if (\App\Document::where('id',$item->id_document)->get())
你可以使用
@if (\App\Document::where('id',$item->id_document)->firstOrFail())
@if (\App\Document::where('id',$item->id_document)->count())
就是这样。