skip to Main Content

When creating a new user in Postgres, I have a trigger that automatically creates a chat for him (like saved messages in telegram). I also have a chat_members table in the database that stores chat members in a many-to-many relationship of users and chats. I need to write a trigger that triggers when creating any chat and will automatically insert its creator to the chat_members table, but I don’t know how to pass the user_id, since there is no such column in the chats table. My db schema on Supabase:

https://phpout.com/wp-content/uploads/2023/08/e9zpG.png

One solution is to add a created_by column in the chat table, and write the chat creator there, and then the trigger takes that id and creates an entry in the chat_members table.

2

Answers


  1. You would just create your trigger and use the auth.uid() as the user_id since the user creating the chat would be signed in I assume. You can access the auth.uid() inside any trigger function.

    Login or Signup to reply.
  2. You definitely need to keep the record of person who created the chat.
    Its good idea to add created_by field in table. But still you will need to add that person in chat_members table. I am expecting that column role will serve for the same purpose.

    You can write a custom function/trigger which inserts in other(chat_members) table.

    Something like this: (pseudocode as i could not test)

    CREATE OR REPLACE FUNCTION insert_chat_member(
        argument1 integer,
        .....,
        .....,
        argumentN datetime
    )
    RETURNS TRIGGER
    LANGUAGE PLPGSQL  
    AS $$
    BEGIN
        INSERT INTO chat_members (chat_id, user_id, role, last_action, created_at)
        VALUES (arguments here);
        RETURN NEW;
    END;
    $$;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search