首页 > 解决方案 > 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>

我还看到,在包含数据的数组之前和之后,有两个空数组,如下图所示:

在此处输入图像描述

有什么我做错了吗?

标签: laravel

解决方案


如果不是所有的属性都有优惠,那么你应该在 之前检查<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();

推荐阅读