I have two tables, group and groupmembers. On insertion of a row in the group table, I also want to insert two values, groupid (id from group table) and userid (id of the user that created the group) into the groupmembers table. These are the tables:
CREATE TABLE groups (
id SERIAL PRIMARY KEY NOT NULL,
name CHARACTER VARYING(255) NOT NULL,
creator CHARACTER VARYING(255) NOT NULL,
role CHARACTER VARYING(100) NOT NULL DEFAULT ('admin'),
createdon TIMESTAMP WITH TIME ZONE DEFAULT now(),
FOREIGN KEY (creator) references users (email) on delete CASCADE
);
CREATE TABLE groupmembers (
id SERIAL PRIMARY KEY NOT NULL,
groupid INTEGER NOT NULL,
userid INTEGER NOT NULL,
createdon TIMESTAMP WITH TIME ZONE DEFAULT now(),
FOREIGN KEY (groupid) references groups (id) on delete CASCADE,
FOREIGN KEY (userid) references users (id) on delete CASCADE
);
CREATE TABLE users (
id SERIAL PRIMARY KEY NOT NULL,
firstname CHARACTER VARYING(255) NOT NULL,
lastname CHARACTER VARYING(255) NOT NULL,
email CHARACTER VARYING(50) UNIQUE NOT NULL,
password CHARACTER VARYING(255) NOT NULL,
registeredon TIMESTAMP WITH TIME ZONE DEFAULT now()
);
The insert statement into the group table is:
INSERT INTO groups (name, creator) VALUES ($1, $2) RETURNING *;
How do I add another insert statement that inserts values into groupid and userid columns of groupmembers table?
I have seen this, but it doesn't seem to answer my question:
PostgreSQL nested INSERTs / WITHs for foreign key insertions