[英]Laravel 5.4 One to Many relationship (check if record exist in pivot table)
我想檢查當前用戶是否已經有這輛車。
User.php:
public function car()
{
return $this->hasMany(Car::class);
}
Car.php
public function user()
{
return $this->belongsTo(User::class);
}
例如,我要通過“汽車”表查看所有汽車,我想檢查當前用戶是否已經擁有該汽車:
@foreach( $cars as $car )
@if(Auth::user()->cars->where('car_id', $car->id)->exists())
You have this car!
@else
Buy this car!
@endif
@endforeach
現在,此代碼返回錯誤:
在null上調用成員函數where()
我如何檢查用戶是否已經有這輛車?
2個問題:
首先,錯字car
/ cars
。
其次,您具有public function car()
因此它應為Auth::user()->car()->where('car_id', $car->id)->exists()
進行條件鏈接。
請查看Laravel 5.4文檔中有關鏈接查詢條件的“一對多”部分 (在該部分的最后)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.