Is there a way to order parent and child in the same table by using supabase-js?
I have a comments
table.
create table
public.comments (
id uuid not null default gen_random_uuid (),
created_at timestamp with time zone not null default now(),
post_id uuid not null,
user_id uuid not null default auth.uid (),
parent_id uuid null,
text text not null,
constraint comments_pkey primary key (id),
constraint comments_parent_id_fkey foreign key (parent_id) references comments (id) on update cascade on delete cascade,
constraint comments_post_id_fkey foreign key (post_id) references posts (id) on update cascade on delete cascade,
constraint comments_user_id_fkey foreign key (user_id) references profiles (id) on update cascade on delete cascade
) tablespace pg_default;
When retrieving data from this table, I want to order the comments such that parent comments appear before their child comments.
For example, given the following rows:
[{id: "a", parent_id: null}, {id: "b", parent_id: null}, {id: "c", parent_id: "a"}}]
I want the outcome to be:
[{id: "a", parent_id: null}, {id: "c", parent_id: "a"}, {id: "b", parent_id: null}}]
Please notice rows that are related to id a
are ordered first and then the rest.
This is what I’ve coded so far:
const { data, error } = await supabase
.from("comments")
.select(`*, profiles(*)`)
.eq("post_id", postId)
.order("created_at", { ascending: false });
Is there a way to achieve the desired ordering using supabase-js? or Should I order on client side? Any guidance or examples would be greatly appreciated. Thank you.