Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

How to add value from one query to another

$
0
0

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?


Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>