Answer the question
In order to leave comments, you need to log in
How to select all subcategories?
There is a catalog with categories, with unlimited nesting. Everything is stored in postgres, a regular table with id and parent_id fields from itself.
How to select all subcategories for the specified id?
Answer the question
In order to leave comments, you need to log in
Use a recursive CTE :
with recursive r as (
select
id, parent_id, name
from catalog_category
where id = 8
union
select
cc.id, cc.parent_id, cc.name
from catalog_category as cc
join r
on cc.parent_id = r.id
)
select id, name from r where id <> 8;
If you need to quickly and in one request, then each element should contain an array (+ index) of all its parents.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question