我的桌子上有多个与vehicle_id
相关的图片,像这样
image table
id fileName vehicle_id
1 1.jpg 1
2 2.jpg 1
3 3.jpg 1
4 4.jpg 1
5 28.png 2
5 28.png 2
6 29.png 2
7 30.png 3
8 31.png 3
9 56.png 3
使用VehicleController
中的eager loader,车辆表与图像表和数据抓取之间有很多关系
$vehicles = Vehicle::with('image')->get();
return view('vechicles.index')->withVehicles($vehicles);
现在这些图像显示在Vehicles / index.blade.php文件中
@foreach($vehicle->images as $image)
<tr>
<td><a href="{{route('vechicles.show',$vehicle->id)}}"><img src="/images/{{ $image->resized_name }}"></a></td>
</tr>
@endforeach
我的问题现在发生了,用这种方式,我可以在表中显示与正确的vehicle_id
相关的所有图像,但是,我只需要显示一张图像(与vehicle_id
匹配)就可以像缩略图一样。上面的线。
那我该如何配置呢?
更新后的控制器
public function index()
{
$vehicles = Vehicle::with('images')->get();
return view('vechicles.index')->withVehicles($vehicles);
}
更新了完整刀片
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($vehicles)
@foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
@foreach($vehicle->images as $image)
<tr>
<td><a href="{{route('vechicles.show',$vehicle->id)}}"><img src="/images/{{ $image->resized_name }}"></a></td>
</tr>
@endforeach
@endforeach
@endif
</div>
</div>
</div>
@endsection
答案 0 :(得分:1)
您正在循环浏览所有图像。您只需使用以下代码即可检索图像:
$vehicle->images()->first()->resized_name
因此您显示图片的代码将是:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
@if($vehicles)
@foreach($vehicles as $vehicle)
{{$vehicle->district}}
{{$vehicle->town}}
{{$vehicle->brand}}
{{$vehicle->model}}
<hr>
<tr>
<td>
<a href="{{route('vechicles.show',$vehicle->id)}}"><img
src="/images/{{ $vehicle->images()->first()->resized_name
}}"></a>
</td>
</tr>
@endforeach
@endif
</div>
</div>
</div>
@endsection
答案 1 :(得分:0)
您可以将limit与with
函数一起使用,例如:
Vehicle::with(['image' => function($query) {
return $query->limit(1);
}])->get();
return view('vechicles.index')->withVehicles($vehicles);
并编写代码以将图像显示为:
<tr>
<td><a href = "{{route('vechicles.show',$vehicle->id)}}"><img src = "/images/{{ $vehicle->images[0]->resized_name }}"></a></td>
</tr>
答案 2 :(得分:0)
您仅可以拍摄第一张图像。但是请注意,您必须验证该车辆是否有任何图像,否则将引发异常。
@if ($vehicle->images->isNotEmpty())
<a href="{{route('vechicles.show',$vehicle->id)}}">
<img src="/images/{{ $vehicle->images->first()->resized_name }}">
</a>
@endif
答案 3 :(得分:0)
您可以使用laravel first()
函数。
$vehicles = Vehicle::->where('vehicle_id', 1)->first();
答案 4 :(得分:0)
您只需要显示刀片中的第一个阵列图像,如下所示:
@foreach ($vehicles as $v)
<img src = "/images/{{ $v->images[0]->resized_name }}"
@endforeach
(or) we can also use the laravel first() function to display the first record image from the collection
@foreach ($vehicles as $v)
<img src = "/images/{{ $v->images->first()->resized_name }}"
@endforeach