试试这个:
上市模式:
public function order(){
return $this->hasOne(Order::class); //without first()
}
用户控制器:
这里我们使用方法
with('order')
用于快速加载
Order
每个的模型
Listing
通过查询检索的模型。所以现在在你的刀片上就不会有不必要的查询了。
当将雄辩的关系作为属性访问时,关系
数据是“延迟加载的”。这意味着关系数据不是
直到您第一次访问该属性时才实际加载。然而,雄辩
可以在查询父模型时“即时加载”关系。
public function viewListings(){
$user = Auth::user();
$listings = $user->listings()->orderBy('created_at','desc')
->with('order')->get();//added with('order')
return view('user.listings', compact('listings'));
}
使用者列表:
你应该使用
order
没有
()
如果需要检索模型。所以如果你想修改
顺序
然后将其用于
()
作为查询生成器,并添加其他约束,如
where
,
orderBy
等等,最后加上
first()
.
在这里你可以理解为什么我们删除了
第一()
从…起
hasOne
在上面
@foreach($listings as $listing)
@if($listing->order->status == 'completed')
{{-- order instead of order() --}}
{{-- Display the listing details here --}}
@endif
@endforeach