I have a postgres database of jobs, locations and countries, where jobs <=> locations
is many-to-many, jobs <=> countries
is many-to-many, and locations <= countries
is one-to-many. A job can belong to a country through 2 different paths:
jobs <=> jobs_locations <=> locations <=> countries
jobs <=> jobs_countries <=> countries
This is my current query:
select
jobs.*,
COALESCE(json_agg(locations) filter (where locations.id IS NOT NULL), '[]') as locations,
COALESCE(json_agg(countries) filter (where countries.id IS NOT NULL), '[]') as countries
from jobs
left join jobs_locations on jobs.id = jobs_locations.job_id
left join locations on jobs_locations.location_id = locations.id
left join countries loc_country on locations.country_id = loc_country.id
left join jobs_countries on jobs.id = jobs_countries.job_id
left join countries on jobs_countries.country_id = countries.id
where loc_country.id = 2 OR countries.id = 2
group by jobs.id;
I'm currently getting the data in this format:
{
id: 1,
...
locations: [
{
id: 10,
name: "Paris",
country_id: 100
}
]
}
I want to get a job in this format:
{
id: 1,
...
locations: [
{
id: 10,
name: "Paris",
country: {
id: 100,
name: "France"
}
}
]
}
How can I do this? It seems like a simple query but I've been trying for hours to get this data in the right format, what am I missing here?