簡體   English   中英

如何使用laravel從數據庫獲取記錄的圖像?

[英]How to get images of a record from database with laravel?

我有兩個表,一個存儲東西信息,一個存儲東西圖像

表的東西

stuff_id |  name  | detail

表圖像

id  | stuff_id  | images

-我的模型關系

-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');
{
{

現在我得到一些東西信息,看起來像這樣:

ID  | Name
1   |[July][1]
2   |[Bona][1]

我需要,如果我單擊該商品的名稱,它將進入該商品具有所有圖像的詳細信息頁面。

我的詳細信息頁面

@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

我的控制器

public function Detail($id){
$getDetails = Image::join('Stuffs', 'stuffs.stuff_id' , '=', 'image.stuff_id')
 ->find($id);
 return view('crud.more_detail', compact('getDetails'));
}
}

這是行不通的,並得到此錯誤

ErrorException in b5e95ef79c2c035f3a379c139e5e7ac6 line 11:
Trying to get property of non-object (View: 
C:\wamp\www\crud\resources\views\crud\more_detail.blade.php)

請幫我謝謝;

使用關系的主要要點之一是您不必手動將表連接在一起。

要獲得帶有圖像的圖像,您只需要做:

$getDetails = Image::with('stuff')->find($id); 
//'stuff' is the name of the method you're using in your model

同樣,使用find()將僅返回該行的id等於$id的行,因此循環遍歷$getDetails將不起作用。 這很可能是您遇到錯誤的原因。

如果要獲取所有圖像及其內容,可以執行以下操作:

$getDetails = Image::with('stuff')->get();

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM