简体   繁体   English

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

[英]Laravel 5.4 One to Many relationship (check if record exist in pivot table)

I want to check if current user already has this car. 我想检查当前用户是否已经有这辆车。

User.php: User.php:

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

Car.php 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 在null上调用成员函数where()

How can I check if User already has this car? 我如何检查用户是否已经有这辆车?

2 Problems: 2个问题:

First the typo car / cars . 首先,错字car / cars

Second, you have public function car() so it should be Auth::user()->car()->where('car_id', $car->id)->exists() for condition chaining. 其次,您具有public function car()因此它应为Auth::user()->car()->where('car_id', $car->id)->exists()进行条件链接。

Check out the "One To Many" Section in Laravel 5.4 Documentation about chaining query conditions (pretty much at the end of the section). 请查看Laravel 5.4文档中有关链接查询条件的“一对多”部分 (在该部分的最后)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM