如何从一个查询到另一个查询增加价值

时间:2020-02-20 09:08:30

标签: javascript node.js postgresql

我正在使用React通过NodeJS将数据发送到我的PostgreSQL数据库。我的歌曲表中有一个外键,它参考专辑表中的ID。我的问题是如何将我的ID从我的第一个INSERT返回(或需要做任何事情)到我的第二个INSERT中的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 => {
      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));

}

我尚未在INSERT歌曲中添加album_id。我在等如何从第二张INSERT中获取专辑ID的价值?

1 个答案:

答案 0 :(得分:1)

由于我在歌曲表中看不到album_id列,因此我没有为此编写查询。

您只需要使用then(album_id)

将最后插入的ID传递给下一个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));

}
相关问题