Created
February 14, 2016 03:13
-
-
Save badri/adb370b78c27e05a7c02 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
CREATE OR REPLACE FUNCTION get_children(genre_id integer) | |
RETURNS json AS $$ | |
DECLARE | |
result json; | |
BEGIN | |
SELECT array_to_json(array_agg(row_to_json(t))) INTO result -- inject output into result variable | |
FROM ( -- same CTE as above | |
WITH RECURSIVE genres_materialized_path AS ( | |
SELECT id, name, ARRAY[]::INTEGER[] AS path | |
FROM genres WHERE parent_id IS NULL | |
UNION ALL | |
SELECT genres.id, genres.name, genres_materialized_path.path || genres.parent_id | |
FROM genres, genres_materialized_path | |
WHERE genres.parent_id = genres_materialized_path.id | |
) SELECT id, name, ARRAY[]::INTEGER[] AS children FROM genres_materialized_path WHERE $1 = genres_materialized_path.path[array_upper(genres_materialized_path.path,1)] -- some column polish for a cleaner JSON | |
) t; | |
RETURN result; | |
END; | |
$$ LANGUAGE PLPGSQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment