Created
October 1, 2018 02:12
-
-
Save ejrh/48c3246f122cb774898036ac1bcf2bc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
WITH RECURSIVE t AS | |
( | |
SELECT id, '{}'::int[] AS parents, 0 AS level | |
FROM z_msg WHERE in_reply_to IS NULL | |
UNION ALL | |
SELECT c.id, parents || c.in_reply_to, level+1 | |
FROM t JOIN z_msg AS s c ON t.id = c.in_reply_to | |
), | |
t2 AS | |
( | |
SELECT c.in_reply_to, json_agg(jsonb_build_object('User', name, 'Comment', c.comment, 'Replies', '{}'::json[]))::jsonb AS js | |
FROM t JOIN z_msg AS c ON t.id = c.id | |
JOIN z_user ON z_user.id = c.user_id | |
WHERE level > 0 AND NOT c.id = ANY(parents) | |
GROUP BY c.in_reply_to | |
UNION ALL | |
SELECT c.in_reply_to, jsonb_build_object('Name', name, 'Comment', c.comment) || jsonb_build_object('Replies', js) AS js | |
FROM t2 JOIN z_msg AS c ON c.id = t2.in_reply_to | |
JOIN z_user ON z_user.id = c.user_id | |
) | |
SELECT jsonb_agg(js) | |
FROM t2 | |
WHERE in_reply_to IS NULL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment