duanche2007
2017-09-19 10:28
浏览 98
已采纳

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?

图片转代码服务由CSDN问答提供 功能建议

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

< strong> User.php:

  public function car()
 {
返回$ this-&gt; hasMany(Car :: class); 
  } 
   
 
 

Car.php

  public function user()
 {  
返回$ this-&gt; belongsTo(User :: class); 
} 
   
 
 

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

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

现在,此代码返回错误:

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

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangou2046 2017-09-19 12:05
    已采纳

    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).

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题