问题
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 HasMany Provinces
public function provinces()
{
return $this->hasMany('App\Province', 'country_id', 'id');
}
Province.php HasMany Cities
public function cities()
{
return $this->hasMany('App\City', 'province_id', 'id');
}
City.php HasMany Areas
public function areas()
{
return $this->hasMany('App\Area', 'city_id', 'id');
}
Area.php BelongsToMany Tours
public function tours()
{
return $this->belongsToMany('App\Tour', 'tour_locations');
}
回答1:
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']);
}
}
Then in your controller:
// ...
$country = Country::find(1);
$tours = $country->tours;
Disclaimer: I'm not involved in this package in any way. I'm just suggesting it because is the simplest way to achieve your desired behavior.
来源:https://stackoverflow.com/questions/55387333/hasmany-deep-relationship