大佬教程收集整理的这篇文章主要介绍了Laravel:嵌套关系中的额外关系,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个经典的嵌套关系:
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);
}
}
以上是大佬教程为你收集整理的Laravel:嵌套关系中的额外关系全部内容,希望文章能够帮你解决Laravel:嵌套关系中的额外关系所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。