Laravel:在视图中一对多检索单个记录

时间:2018-06-15 04:55:35

标签: php laravel-blade laravel-5.6

我目前正在学习Laravel 5.6。所以我的问题是这个,我有以下模型:

@extends('layouts.app')

@section('content')
<div class="col-md-8 offset-md-2">
    <br/>
    <table class="table">
        <thead>
            <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Picture</th>
            <th scope="col">Price</th>
            </tr>
        </thead>
        <tbody>
            @foreach($tours as $tour)
                <tr>
                    <th scope="row">{{ $tour->id }}</th>
                    <td>{{ $tour->name }}</td>
                    <td><img src="/storage/{{ $tour->tourImages->path }}" width="200px"/></td>
                    <td>{{ $tour->price }}</td>
                </tr>   
            @endforeach            
        </tbody>
    </table>
</div>
@endsection

所以1巡演可以有多个TourImages。我想要做的是我想打印索引页面上的所有游览。但我只想为每次巡演拍摄一个TourImage文件。我只从控制器返回所有巡回赛的数组。有没有办法可以直接在刀片视图上检索图像而无需从控制器返回更多变量?

以下是我为索引方法编写的内容:

Print

这是我的索引视图:

BSTprint

3 个答案:

答案 0 :(得分:0)

你需要使用with()来获取记录。就像这样。

$tours = Tour::with('tourImages')->where('province_id', $province_id)->get();

答案 1 :(得分:0)

您可以在Tour模型中添加新关系,例如

public function latestTourImage() {
    return $this->hasOne('App\TourImage')->latest();
}

然后您可以在控制器文件中使用它来获取它

$tours = Tour::with('latestTourImage')->where('province_id', $province_id)->get();

然后您可以将其打印在您的刀片文件中,如

$tour->latestTourImage->path

答案 2 :(得分:0)

您可以通过以下代码传递每个游览的一张图片:

$tours=Tour::with(['tourImages'=>function($query){ 
    $query->first(); 
}])->get();

view

@foreach($tours as $tour)
    @if ($tour->tourImages->count())
        <img src="/storage/{{ $tour->tourImages[0]->path }}" width="200px"/>
    @endif
@endforeach