SELECT ROW_TO_JSON(T)
FROM (
SELECT t1.id,
t1.name,
array_to_json(array((
select case when t2.id is not null then row_to_json(t2)
when t3.id is not null then row_to_json(t3)
when t4.id is not null then row_to_json(t4)
end
from public.relation r
LEFT JOIN public.table1 t2 on r.table2 = t2.id
LEFT JOIN public.table1 t3 on r.table3 = t3.id
LEFT JOIN public.table1 t4 on r.table4 = t4.id
where r.table1 = t1.id
))) related_items
FROM public.table1 t1
) T