在Laravel 5.2中按ID显示图像文件 [英] Show image file by id in Laravel 5.2

查看:41
本文介绍了在Laravel 5.2中按ID显示图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为files的表,它保存了与属性表相关的图像的名称.

I have a table named files, this saves the name of the images related to the properties table.

我试图使这些图像按照以下关系显示.

I am trying to make these images appear as in the following relation.

这是属性表的一部分.

这是表文件及其与属性表的关系.

This is the table files and their relationship to the properties table.

我可以在控制器(PropertyController)的show方法中传递什么参数?

What parameter can I pass in the show method of my controller (PropertyController)?

当前,我有以下内容:

public function show($id)
{
 $properties = Property::find($id);

 $files = File::all();

 return View::make('properties.show', ['properties' => $properties, 'files' => $files]);
}

但是它会返回文件表中存储的所有图像.

But it returns to the view all the images stored in the files table.

@foreach($files as $file) 

    <div class="col-md-6 thumb">
        <a class="thumbnail">
            <img id="myImg" src="{{ URL::asset('uploads/products/' . $file->name) }}" alt="{{ $file->name }}" width="300" height="200">
        </a>
    </div>

@endforeach

哪种方法是正确的,以便可以在属性表中按id显示与记录相关的图像?

Which method would be correct so that the images related to the records can be displayed by id in the properties table?

推荐答案

我假设您正在使用PropertyFile模型之间的hasMany()关系.如果不是,请在Property模型中创建关系:

I'm assuming you're using hasMany() relationship between Property and File models. If not, create the relation in the Property model:

public function files()
{
    return $this->hasMany('App\File');
}

要使用其所有图像加载属性,请使用快速加载 :

To load the property with all it's images use eager loading:

public function show($id)
{
    $property = Property::with('files')->find($id);
    return view('properties.show', compact('property'));
}

显示图像:

@foreach($property->files as $file) 
    // Here use the same code you used before.
@endforeach

或者,您可以分别加载数据:

Alternatively, you can load data separately:

public function show($id)
{
    $property = Property::find($id);
    $files = File::where('property_id', $property->id)->get();
    return view('properties.show', compact('property', 'files'));
}

这篇关于在Laravel 5.2中按ID显示图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆