Laravel 5.4一对多关系(检查数据透视表中是否存在记录)

Laravel 5.4一对多关系(检查数据透视表中是否存在记录)

问题描述:

I want to check if current user already has this car.

User.php:

public function car()
    {
        return $this->hasMany(Car::class);
    }

Car.php

public function user()
    {
       return $this->belongsTo(User::class);
    }

For example, I'm passing to view all cars from cars table and I want to check if current user already has this car:

@foreach( $cars as $car )

   @if(Auth::user()->cars->where('car_id', $car->id)->exists())

        You have this car!

   @else

        Buy this car!

   @endif

@endforeach

Now, this code returns an error:

Call to a member function where() on null

How can I check if User already has this car?

我想检查当前用户是否已经拥有此车。 p>

User.php: strong> p>

  public function car()
 {
返回$ this-> hasMany(Car :: class); 
  } 
  code>  pre> 
 
 

Car.php strong> p>

  public function user()
 {  
返回$ this-> belongsTo(User :: class); 
} 
  code>  pre> 
 
 

例如,我要传递查看汽车表中的所有汽车 我想检查当前用户是否已经拥有这款车: p>

  @foreach($ cars as $ car)
 
 @if(Auth :: user() -  > cars-> where('car_id',$ car-> id) - > exists())
 
你有这辆车!
 
 @else 
 
购买这款车!  n 
 @endif 
 
 @ endforeach 
  code>  pre> 
 
 

现在,此代码返回错误: p>

调用成员函数where()on null p> blockquote>

如何检查用户是否已经拥有此车? p> div>

2 Problems:

First the typo car/cars.

Second, you have public function car() so it should be Auth::user()->car()->where('car_id', $car->id)->exists() for condition chaining.

Check out the "One To Many" Section in Laravel 5.4 Documentation about chaining query conditions (pretty much at the end of the section).