acpatrice
08/18/2021, 8:04 PMsilentworks
08/18/2021, 8:12 PMacpatrice
08/18/2021, 8:13 PMparent_id
where null
would be the highest upsilentworks
08/18/2021, 8:13 PMsilentworks
08/18/2021, 8:14 PMsilentworks
08/18/2021, 8:14 PMacpatrice
08/18/2021, 8:16 PMflorian-lefebvre
08/18/2021, 9:20 PMflorian-lefebvre
08/18/2021, 9:21 PMpgsql
drop function if exists public.category_hierarchy;
create function public.category_hierarchy(id_param int)
returns table (
id bigint,
title varchar,
parent_id bigint
)
as $$
begin
return query with recursive parents
as (
select
c1.id,
c1.title,
c1.parent_id
from categories c1
where c1.id = id_param
union
select
c2.id,
c2.title,
c2.parent_id
from categories c2
inner join parents p on p.parent_id = c2.id
) select * from parents;
end;
$$ language plpgsql security definer;
acpatrice
08/18/2021, 9:41 PMacpatrice
08/18/2021, 9:43 PMflorian-lefebvre
08/19/2021, 7:44 AMflorian-lefebvre
08/19/2021, 7:44 AMflorian-lefebvre
08/19/2021, 7:44 AMselect * from category_hierarchy(5)
florian-lefebvre
08/19/2021, 7:46 AM[
{Id: 5, title: "Category 5", parent_id: 4},
{Id: 4, title: "Category 4", parent_id: 3},
...
{Id: 1, title: "Category 1", parent_id: null}
]