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:
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
You would just create your trigger and use the
auth.uid()
as theuser_id
since the user creating the chat would be signed in I assume. You can access theauth.uid()
inside any trigger function.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 inchat_members
table. I am expecting that columnrole
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)