laravel - Laravel 数组在数据数组之前显示为空
问题描述
我有一个拥有许多属性的用户。这是用户还应该能够查看对他的属性下注的优惠。
所以设置了关系。
用户.php
public function properties(){
return $this->hasMany('App\Property');
}
属性.php
public function offers(){
return $this->hasMany('App\Offer');
}
然后在我的控制器中,这就是我所拥有的:
public function my_offers(){
$properties = Property::whereUserId(Auth::id())->get();
return view('pages.seller.offers.index', compact('properties'));
}
然后我去我的观点是这样的:
@if($properties)
<ul>
@foreach($properties as $property)
<li>{{$property->offers->offer_message}}</li>
@endforeach
</ul>
@endif
当我查看页面时,我看到以下错误:
此集合实例上不存在属性 [offer_message]。
但是这个属性存在于我的表中。
如果我将列表项更改为下面的项,我可以看到数组:
<li>{{$property->offers}}</li>
我还看到,在包含数据的数组之前和之后,有两个空数组,如下图所示:
有什么我做错了吗?
解决方案
如果不是所有的属性都有优惠,那么你应该在 之前检查<li>
,除此之外,offers
是一个集合,你需要遍历它,这就是你得到错误的原因。
@if($properties)
@php ($i = 1)
<ul>
@foreach($properties as $property)
@if ($property->offers)
@foreach ($property->offers as $offer)
<li>Offer {{ $i++ }}: {{$offer->offer_message}}</li>
@endforeach
@endif
@endforeach
</ul>
@endif
如果您只想获取具有优惠的 de 属性(查询关系存在):
$properties = Property::whereUserId(Auth::id())->has('offers')->get();
你可能应该急切地加载这种关系:
$properties = Property::whereUserId(Auth::id())->has('offers')->with('offers')->get();
推荐阅读
- movesense - J-Flash (Lite) 程序 Movesense
- xml - 使用 xslt 从 xml 输入中删除换行符
- php - 如何使用 PHP 查找和替换字符串中的多个值
- excel - 循环遍历列中的所有单元格,如果找到匹配项,则复制并粘贴文本
- php - 在刀片视图中显示数组数据 - Laravel
- python - 在超类中使用描述符以避免子类中的代码重复
- python - 如何安装 scikit-learn 0.21.2 版?
- android - 我希望我的应用程序能够识别同时按住两个按钮的时间
- google-apps-script - Google Script Document Inaccessible Error - 在代码中创建并尝试打开文档
- ruby-on-rails - 如何使我的回复达到要求的标准