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

mooseh's avatar

one to many and many to one middle table

Hi everyone I am having a bit of trouble with some tables im working with

I have three tables

  1. Continents continent_id, continent_code, continent_name, display
  2. Locations location_id, continent_code, country_code
  3. countries country_id, country_code, country_name, display

Thing is I dont know why someone designed it like this with a middle table as its not like you have many continents in a country, but still I have to work with it and im having huge troubles.

So i want to get all of a continents countries with using a hasmanythrough but i just cannot for the life of me get it to work, I know there are alot of fields in here that dont do it the "eloquent" way so i've had to put all the custom feilds in to even get it to try let alone work. The joiner table is locations and what we have for example data is

00001 , EU, UK, 1 which is AI primary key, continent_code, country_code, 1 to display

App\Geo\Continent.php

    public function Countries()
    {
        return $this->hasManyThrough(Location::class, Country::class, 'country_code','continent_code', 'continent_code');
    }

when i try below i just get an empty array, but i know there are some there

$continent = Continent::first();

        $countries = $continent->Countries()->get();

        dd($countries);

**UPDATE *** This is what i need in SQL

select `geo_locations`.*, `geo_countries`.`country_name` from `geo_locations` inner join `geo_countries` on `geo_countries`.`country_code` = `geo_locations`.`country_code` where `geo_locations`.`continent_code` = ?

This is what im getting which is obviously wrong select `geo_locations`.*, `geo_countries`.`country_code` from `geo_locations` inner join `geo_countries` on `geo_countries`.`country_id` = `geo_locations`.`country_code` where `geo_countries`.`country_code` = ?

0 likes
0 replies

Please or to participate in this conversation.