【问题标题】:Trouble fetching data from 1 to 1 relationsip Laravel从 1 对 1 关系 Laravel 获取数据时遇到问题
【发布时间】:2017-06-14 07:02:53
【问题描述】:

我在表格中设置了两个模型。并制作了一个表格来填写两个表格,并且效果很好

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-&gt;featuredimage-&gt;path}}

错误是

Trying to get property of non-object

在线{{$featured-&gt;featuredimage-&gt;path}}。我在之前的项目中使用过这种方法,效果很好,但在这个项目中并不顺利。

我尝试用{{$featured-&gt;featuredImage-&gt;path}} 替换{{$featured-&gt;featuredimage-&gt;path}},但没有成功。

【问题讨论】:

  • 什么是withTours

标签: php laravel laravel-5.3 laravel-blade


【解决方案1】:

这样做:

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

此外,您还在这里创建了许多额外的查询。你应该使用eager loading来解决N+1问题:

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

并显示数据:

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

【讨论】:

  • 没有成功。现在错误是Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$path
  • 还是没有运气。错误是Trying to get property of non-object ,您在评论中建议的方法。
  • @ZacharyDale 你确定每次巡演都有特色图片吗?
  • 是的,老板我确定。我可以看到旅游的名字。两个表都填满了 6 行。
  • 你有旅游的名字,但你有每个旅游的特色图片吗?因为它是一对一的,所以 toursfeatured_images 表中的行数应该相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-19
  • 1970-01-01
  • 2022-11-10
相关资源
最近更新 更多