[英]How to get images of a record from database with laravel?
I have two tables one store stuff information and one store stuff images 我有两个表,一个存储东西信息,一个存储东西图像
-table stuffs 表的东西
stuff_id | name | detail
-table images 表图像
id | stuff_id | images
-my model relationship -我的模型关系
-Stuffs
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Stuffs extends Model
{
// A Stuff has many images
public function image(){
return $this->hasMany('App\Model\image', 'stuff_id');
}
}
-Image
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
{
// images belongs to only one Stuff
public function stuff(){
return $this->belongsTo('App\Model\Stuffs');
{
{
Now I get some stuff info and look like this: 现在我得到一些东西信息,看起来像这样:
ID | Name
1 |[July][1]
2 |[Bona][1]
I need that if I click on that stuff's name it will go to detail page with all the images of the stuff has. 我需要,如果我单击该商品的名称,它将进入该商品具有所有图像的详细信息页面。
My Detail Page 我的详细信息页面
@foreach($getDetails as $getDetail)
<a rel="lightbox" data-lightbox = "gallery" href="{{URL::asset($getDetail->images)}}">
<img class="img-responsive" width="150" src="{{URL::asset($getDetail->images)}}">
</a>
@endforeach
My Controller 我的控制器
public function Detail($id){
$getDetails = Image::join('Stuffs', 'stuffs.stuff_id' , '=', 'image.stuff_id')
->find($id);
return view('crud.more_detail', compact('getDetails'));
}
}
It is not work and get this error 这是行不通的,并得到此错误
ErrorException in b5e95ef79c2c035f3a379c139e5e7ac6 line 11:
Trying to get property of non-object (View:
C:\wamp\www\crud\resources\views\crud\more_detail.blade.php)
Please help me thanks; 请帮我谢谢;
One of the main points of using relationships is that you don't have to manually join tables together. 使用关系的主要要点之一是您不必手动将表连接在一起。
To get an image with it's stuff you would just need to do: 要获得带有图像的图像,您只需要做:
$getDetails = Image::with('stuff')->find($id);
//'stuff' is the name of the method you're using in your model
Also, using find()
will only return the row where the id of that row is equal to $id
so looping through $getDetails
won't work. 同样,使用
find()
将仅返回该行的id等于$id
的行,因此循环遍历$getDetails
将不起作用。 This is most likely the reason you're getting an error. 这很可能是您遇到错误的原因。
If you want to get all images and their stuff you could do: 如果要获取所有图像及其内容,可以执行以下操作:
$getDetails = Image::with('stuff')->get();
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.