有很多深厚的关系 [英] HasMany Deep Relationship
问题描述
我有5个带有一个数据透视表的模型Country
Province
City
Area
Tour
tour_location
.如何实现以下功能?
I have 5 models with one pivot table Country
Province
City
Area
Tour
tour_location
. How to achieve below functionality?
$country->tours
$province->tours
$city->tours
$area->tours
Country.php 有许多省份
Country.php HasMany Provinces
public function provinces()
{
return $this->hasMany('App\Province', 'country_id', 'id');
}
Province.php 许多城市
Province.php HasMany Cities
public function cities()
{
return $this->hasMany('App\City', 'province_id', 'id');
}
City.php 有许多地区
City.php HasMany Areas
public function areas()
{
return $this->hasMany('App\Area', 'city_id', 'id');
}
Area.php 属于许多游览
Area.php BelongsToMany Tours
public function tours()
{
return $this->belongsToMany('App\Tour', 'tour_locations');
}
推荐答案
直接方法是对join
执行此操作,另一种方法是建立扩展hasManyThrough()
的自定义关系.第三个选项-imo-是使用 Eloquent-has-many-deep 包装.
The direct way is do it with join
s, another way is to make a custom relationship extending the hasManyThrough()
. The third option -imo- is to use the Eloquent-has-many-deep package.
使用此软件包,您可以执行以下操作:
Using this package, you could do this:
class Country extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function tours()
{
return $this
->hasManyDeep('App\Tour', ['App\Province', 'App\City', 'App\Area', 'area_tour']);
}
}
然后在您的控制器中:
// ...
$country = Country::find(1);
$tours = $country->tours;
免责声明:我不以任何方式参与此程序包.我只是建议这样做,因为这是实现所需行为的最简单方法.
这篇关于有很多深厚的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!