HasMany Deep Relationship

回眸只為那壹抹淺笑 提交于 2020-01-06 06:54:59

问题


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 joins, 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!