I know we are all using a bunch of ORMs for SQL, but I wanted to give a try to native drivers. What is the correct way to map the data after executing Postgres Join? Please see the two queries below.
I have tables:
articles (id, title, text)
comments (id, article_id, text)
The data I want to pass back to the client is an array of articles, and each article has an array of comments:
[{ id: 1,
title: "Article 1",
text: "Random text",
comments: [{
id: 1,
article_id: 1,
text: "Hello",
}],
}];
I could achieve this using two different approaches.
SELECT a.id, a.title, c.id, c.text, c.article_id
FROM articles a JOIN "comments" c ON a.id = c.article_id
or
SELECT a.id, a.title, array_agg((c.id, c.text, c.article_id)) AS comments
FROM articles a
JOIN comments c ON a.id = c.article_id
GROUP BY c.article_id
- First query: I will need to group data manually on the backend by c.article_id
- Second query: It will group it by PostgreSQL and create an array, but is this the correct approach?
I am specifically asking for 'every-day use', which means a bit greater tables. Or maybe you know some other approach? I would love to know if any of these approaches are popular ORMs using because with ORMs you can easily get the data as it is in the example of articles array above