Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

iffifan's avatar

distant relations via many-to-many relation

I have 3 tables: regions, countries, tours

region has countries and country is related to a region

tours have countries and countries have tours.

Now I need Region has tours and tour has regions (tour can include more than one region depending upon countries it belongs to)

I know "Has Many Through" but this is usable when intermediate relation is one-to-many but my intermediate relation is many-to-many

0 likes
7 replies
midascodebreaker's avatar

nested relationship can , or distant can be eagerloaded with dot annotation Region::with('countries.tours')->get()

As long as you define the relationship you have no problem at all

iffifan's avatar

$region->tours will not work with above sooution.

I want to use it for something like this: Tour::where('region_id', $region->id)->get();

Is this possible?

iffifan's avatar

Anyone?

for example how should i get total tours in a region?

midascodebreaker's avatar
Level 17

in an eager loaded relationship... you just query it as normal

$region->countries()->find('id_of_country')->tours()->get()

get the instance of the region.. then find the country you want then load its tours... it is simple as that

2 likes
iffifan's avatar

@supervip this seems better to me

@willvincent I know "Has Many Through" but this is usable when intermediate relation is one-to-many but my intermediate relation is many-to-many How will it work with many-to-many intermediate relation?

iffifan's avatar

I tried this

public function tours()
    {
        return $this->hasManyThrough(Tour::class, Country::class, "region_id", "country_id");
    }

but "country_id" is not available in Tours table. Because Tours and Countries has many to many relation and country_id is in pivot table.

Please or to participate in this conversation.