With reference to this question and this SQL Fiddle, I currently have a working SQL query, based off of this answer, that gets a tag from the database and aggregates all articles having such a tag. The current query is:
SELECT
t.id AS t_id,
t.name AS t_name,
t.description AS t_description,
json_agg(
jsonb_build_object(
'id', a.id,
'fore_image', a.fore_image,
'title', a.title,
'slug', a.slug,
'content', a.content,
'is_published', a.is_published,
'created_at', a.created_at,
'updated_at', a.updated_at,
'author', jsonb_build_object(
'id', u.id,
'email', u.email,
'first_name', u.first_name,
'last_name', u.last_name,
'is_active', u.is_active,
'is_staff', u.is_staff,
'is_superuser', u.is_superuser
)
)) AS articles
FROM tags AS t
JOIN articles_tags AS a_t ON a_t.tag_id = t.id
JOIN articles AS a ON a_t.article_id = a.id
JOIN users AS u ON a.user_id = u.id
WHERE t.Id = 3
GROUP BY t.id;
But at present, json_agg()
is fetching all related articles at once which will be inefficient in the long run. Is there a way I can introduce LIMIT
and OFFSET
to json_agg()
so I can control the number of articles a query produces?