I would like to add data to two tables in Postgres with one query using CTE. After a user submit data from a form in the frontend for table2, I want my SQL query to insert id, value1 in table1. Then the same id in table one will be used to create data of table2. When I tried the hard-coded value below in pgAdmin, the code works as the id was generated for table1 and used to create table2 data.
WITH ins AS (
INSERT INTO table1
(post_type, created_on)
VALUES
('keyword', 'NOW()')
RETURNING pid)
INSERT INTO table2
(pid, author, title, description, body, category, search_volume, is_deleted, created_on)
VALUES
((SELECT pid FROM ins), 'jet12', 'Head', 'Head is on top', 'Head is the most important part of the body', 'Head', '10000', 'false', 'NOW()')
However, since I'll be using a form to populate the data, hard-coding will surely not work. I tried the code below but I can't seem to get around it.
WITH ins AS (
INSERT INTO table1
(post_type, created_on)
VALUES
('keyword', 'NOW()')
RETURNING pid)
INSERT INTO table2
(pid, author, title, description, body, category, search_volume, is_deleted, created_on)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
Please how can I write the query to accept parameters as values? Is there another way to go about it? See my full function below:
const keywordHandler = (req, res) => {
const values = [req.body.pid, req.body.username, req.body.title, req.body.description, req.body.body, req.body.category, req.body.search_volume, req.body.is_deleted, req.body.created_on]
pool.query(`WITH ins AS (
INSERT INTO table1
(post_type, created_on)
VALUES
('keyword', 'NOW()')
RETURNING pid)
INSERT INTO table2
(pid, author, title, description, body, category, search_volume, is_deleted, created_on)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
values, (k_err, k_res) => {
if (k_err) {
return console.error('Error executing query', k_err.stack)
}
res.json({
status: 'Keyword submitted successfully',
data: k_res.rows
});
})
};