Search code examples
javascriptnext.jssupabase

how to insert data into table that has 2 columns in which col1 refers col2


I successfully inserted data by passing in hardcoded values (see 1st code snippet) to verify the relation between the 2 columns is valid.

I want to know if there is a way to reference id's value in reply_id

This is how I did manually inserted data:

    const { data, error } = await supabaseServer.from('replies').insert({
        text: 'some text',
        id: 'e888f9c5-15b1-4e84-90bc-8bc2128a9338',
        reply_id: 'e888f9c5-15b1-4e84-90bc-8bc2128a9338'
    })

This is the Table schema in Supabase and a picture of the relation for readability:

  public.replies (
    id uuid not null,
    text text not null,
    reply_id uuid null,
    constraint replies_pkey primary key (id),
    constraint replies_reply_id_fkey foreign key (reply_id) references replies (id) on delete cascade,

  )

enter image description here

I miserably failed when trying the following as I simply referenced id in reply_id. What can i do differently?:

        text: replyText,
        id: randomUUID(),
        reply_id: id
    })

Solution

  • Is this what you want?

    const id = randomUUID()
    const { data, error } = await supabaseServer.from('replies').insert({
      text: 'some text',
      id: id,
      reply_id: id,
    })