无法从1对1关系Laravel中获取数据

时间:2017-01-28 18:57:28

标签: php laravel laravel-5.3 laravel-blade

我已经在表格中设置了两个模型。并制作了一个表单来填充两个表格,它完美地运作

Tour.php

public function featuredImage()
{
  return $this->hasOne('App\FeaturedImage');
}

tours

id|name|content|featured_status

featuredImage.php

public function tour()
{
  return $this->belongsTo('App\Tour');
}

Featured_imagesid|tour_id|path|name

我的控制器中的代码将数据传递给查看。

$tours = Tour::where('featured', 1)->get();
return view('public.pages.index')
        ->withTours($tours);

我认为的代码

@foreach($tours as $featured)
<div class="thumbnail">
   <img src="{{$featured->featuredimage->path}}" alt="{{$featured->featuredImage->name}}">
</div>
<h4>{{$featured-name}}</h4>
@endforeach

问题是我无法通过编写

来获取特色图像

{{$featured->featuredimage->path}}

,错误是

Trying to get property of non-object

{{$featured->featuredimage->path}}行。我在之前的项目中使用过这种方法,它运行得很好但是在这一方面进展不顺利。

我尝试将{{$featured->featuredimage->path}}替换为{{$featured->featuredImage->path}},但没有解决问题。

1 个答案:

答案 0 :(得分:0)

这样做:

{{ $featured->featuredImage()->path }}

此外,您在此处创建了许多其他查询。您应该使用eager loading来解决N + 1问题:

$tours = Tour::with('featuredImage')->where('featured', 1)->get();

显示数据:

{{ $featured->featuredImage->path }}