I'm trying to make a query to get a report and all of the report_items associated with the report.
reports table structure: id | name | creation_date
report_items table structure: id | report_id | place | producer | serial_number
I tried this:
SELECT "reports".*,
to_json("report_items".*) as "items"
FROM "reports" INNER JOIN "report_items" USING ("id")
WHERE "reports".id = ${req.params.id}
but only the first report_item returns (instead of a list of report_items):
{"id":1,"type":"fd","name":"dsfdsfds","client_name":"fdsfds","website":"dsffds","creation_time":"2019-03-12T22:00:00.000Z","items":{"id":1,"report_id":1,"place":"saddsa","type":"sdadsa","producer":"sdadsa","serial_number":"adsdsa","next_check_date":"2019-03-19","test_result":"saddsa","comments":"saddsa"}}
Expected result:
{"id":1,"type":"fd","name":"dsfdsfds","client_name":"fdsfds","website":"dsffds","creation_time":"2019-03-12T22:00:00.000Z","items": [{"id":1,"report_id":1,"place":"saddsa","type":"sdadsa","producer":"sdadsa","serial_number":"adsdsa","next_check_date":"2019-03-19","test_result":"saddsa","comments":"saddsa"}, {"id":1,"report_id":1,"place":"saddsa","type":"sdadsa","producer":"sdadsa","serial_number":"adsdsa","next_check_date":"2019-03-19","test_result":"saddsa","comments":"saddsa"}]}
Any idea what I'm missing?
a long solution I can do (pretty sure it's not ideal..):
SELECT * FROM reports
WHERE id = ${req.params.id}
SELECT * FROM report_items
WHERE report_id = ${req.params.id}
and combine them programmatically.
to_jsoninto an array aggregation, e.g.:array_to_json(array_agg(to_json(report_items.*))) AS itemsError: error: column "reports.id" must appear in the GROUP BY clause or be used in an aggregate function