简体   繁体   English

Laravel:使用带有 where 子句的 pivot 表获取单个 model

[英]Laravel: Get single model using pivot table with where clause

I've got 3 tables:我有 3 张桌子:

  • Car: belongsToMany Owner车:belongsToMany Owner
  • Owner: belongsToMany Car车主:belongsToMany Car
  • CarOwner: pivot table for Car and Owner with an additional column 'active' that indicates who is the current Owner of a Car CarOwner:汽车和车主的 pivot 表,附加列“活动”表示谁是汽车的当前车主

So a Car might have multiple or no Owners and vica versa BUT a Car has only 1 current ('active') Owner.因此,汽车可能有多个或没有所有者,反之亦然,但汽车只有一个当前(“活动”)所有者。

 class Car extends Model { use HasFactory; public function owners() { return $this->belongsToMany(Owner::class, 'car_owners'); } public function currentOwner() { return $this->owners()->where('active', true)->first(); } }

My problem is if a Car has no active Owner, Laravel throws the following exception when I want to use $car->currentOwner in a Blade template:我的问题是如果汽车没有活动所有者,当我想在Blade模板中使用$car->currentOwner时,Laravel 会引发以下异常:

App\Models\Car::currentOwner must return a relationship instance, but "null" was returned. Was the "return" keyword used?

How can I handle if a Car doesn't have any active Owners?如果汽车没有任何活跃的车主,我该如何处理?

You can create a custom attribute instead of a relation function:您可以创建自定义属性而不是关系 function:

    public function getCurrentOwnerAttribute()
    {
        return $this->owners()->where('active', true)->first();
    }

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

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