如何使用laravel从数据库中获取记录的图像?

时间:2015-08-17 05:28:36

标签: php image laravel laravel-5

我有两个表一个商店的东西信息和一个商店的东西图像

-table stuffs

stuff_id |  name  | detail

- 表格图片

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

现在我得到一些东西信息,看起来像这样:

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)

请帮助我谢谢;

1 个答案:

答案 0 :(得分:0)

使用关系的一个要点是您不必手动连接表。

要获得带有它的图像,您只需要这样做:

$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();

希望这有帮助!