I am trying to have my query return JSON to be used in an API. I am using the PostGIS extension to deal with location information. The PostGIS extension is working well and not an issue with this problem. I only mention this because there are functions in the query related to the PostGIS extension. I have these objects of the JSON document:
- main Company document (OK)
- Events related to companies (OK)
- Dates related to the Events (* this is where we have a problem)
- Addresses related to Companies (OK)
- Cities related to Companies (OK)
Here is my SQL statement:
SELECT c.id, c.name, c.website, c.longdescription, c.description, c.email,
jsonb_agg((SELECT ev FROM (SELECT ev.title, ev.description, ev.longdescription, jsonb_agg((SELECT ed FROM(SELECT ed.startdate, ed.enddate, ed.id WHERE ed.id notnull)ed)) AS dates, ev.id WHERE ev.id notnull)ev)) AS events,
jsonb_agg((SELECT ca FROM (SELECT ct.zip, ca.id, ca.street1, ca.street2, ca.addresstype_id, ST_Y(ca.geopoint::geometry) AS latitude, ST_X(ca.geopoint::geometry) AS longitude WHERE ca.id notnull)ca)) AS addresses
FROM companies c
LEFT JOIN events ev ON ev.company_id = c.id
LEFT JOIN companyaddresses ca ON ca.company_id = c.id
LEFT JOIN cities ct ON ct.id = ca.city_id
LEFT JOIN eventdates ed ON ed.event_id = ev.id
GROUP BY c.id
Any ideas how I could reform as not to have the nested functions and still arrive at the correct result?