[英]Laravel: Get single model using pivot table with where clause
I've got 3 tables:我有 3 张桌子:
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.