Laravel: 嵌套关系中的额外关系

Laravel: Extra relation in a nested relationship

我有一个经典的嵌套关系:

User hasMany licences

Licence belongsTo User
Licence hasMany attestations

Attestation belongsTo Licence
Attestation hasMany vehicles

Vehicle belongsTo Attestation

现在,出于实际原因,我需要添加与层次结构中最低项的额外关系:

Licence hasMany vehicles

和可选的:
Vehicle belongsTo Licence

我想知道这样做是否可行和安全,是否没有副作用。

在 Laravel 版本 8.x 中,您可以根据他们的文档 https://laravel.com/docs/8.x/eloquent-relationships#has-many-through 尝试 HasManyThrough。在您的情况下,它将是这样的:

class Licence extends Model
{
    //...

    /**
     * Get all of the vehicles for the licence.
     */
    public function vehicles()
    {
        return $this->hasManyThrough(Vehicle::class, Attestation::class);
    }
}

BelongsTo 不是这样工作的,您必须使用 https://laravel.com/docs/8.x/eloquent-relationships#has-one-through

class Vehicle extends Model
{
    //...

    /**
     * Get all of the vehicles for the licence.
     */
    public function licence()
    {
        return $this->hasOneThrough(Licence::class, Attestation::class);
    }
}