I'm using React to send data to my PostgreSQL database using NodeJS. I have a foreign key in my songs table that REFERENCES to the id in my albums table. My question is how can I return (or whatever needs to be done) my id from my first INSERT to the album_id in my second INSERT? Here's my code currently:
const addData = (request, response) => {
const uuid = uuidv4();
db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
.then(res => {
console.log('INSERT ' + JSON.stringify(res.rows[0].id));
}).then(() => {
for (let i = 0; i < request.body.files.length; i++) {
db.pool.query('INSERT INTO songs (id, name, link, index) VALUES ($1, $2, $3, $4) ON CONFLICT (album_id, index) DO NOTHING RETURNING *', [uuidv4(), request.body.files[i].name, request.body.files[i].link, request.body.files[i].index])
}
}).then(res => {
console.log('INSERT INTO songs ' + JSON.stringify(res));
}).catch(error => console.log(error));
}
I haven't added album_id yet to my songs INSERT. I'm waiting to see how I can get the value from id of albums into my second INSERT?
As I can not see the album_id
column in songs table so I am not writing the query for that.
You just need to pass that last inserted id to the next using then(album_id)
const addData = (request, response) => {
const uuid = uuidv4();
db.pool.query('INSERT INTO albums (title, date, description, id) VALUES ($1, $2, $3, $4) ON CONFLICT (id) DO NOTHING RETURNING *' , [request.body.title, request.body.date, request.body.description, uuid])
.then(res => {
let album_id = res.rows[0].id;
console.log('INSERT ' + JSON.stringify(res.rows[0].id));
}).then((album_id) => {
console.log("album_id " + album_id);
// here you will get the album id and now you can use it as per required.
.....
.....
//
}).then(res => {
console.log('INSERT INTO songs ' + JSON.stringify(res));
}).catch(error => console.log(error));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.