我有一个典型的嵌套关系:
User hasMany licences
Licence belongsTo User
Licence hasMany attestations
Attestation belongsTo Licence
Attestation hasMany vehicles
Vehicle belongsTo Attestation
现在,出于实际原因,我需要添加一个与层次结构中最低项的额外关系:
Licence hasMany vehicles
并可选择:
Vehicle belongsTo Licence
我想知道这样做是否可行和安全,是否有副作用。
发布于 2021-03-09 08:09:58
在Laravel8.x版本中,您可以尝试HasManyThrough,根据他们的文档https://laravel.com/docs/8.x/eloquent-relationships#has-many-through。在你的例子中,它应该是这样的:
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);
}
}https://stackoverflow.com/questions/66542248
复制相似问题