【问题标题】:How to add value from one query to another如何将一个查询的值添加到另一个查询
【发布时间】:2020-02-20 17:21:45
【问题描述】:

我正在使用 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 中添加专辑 ID。我在等着看如何将专辑 id 的值获取到我的第二个 INSERT 中?

【问题讨论】:

  • console.log 在查询后立即插入专辑表记录专辑 ID,是吗?
  • 请提供您的表格结构

标签: javascript node.js postgresql


【解决方案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));

}

【讨论】:

  • 我所做的是在所有查询之前设置let album_id;,然后在第一个查询之后添加album_id = res.rows[0].id;,然后在第二个查询中设置album_id。你的代码虽然帮助了我。如果我应该对我的代码进行任何调整,请告诉我。
  • 关于代码中的更改,根据我的回答,现在您可以获得album_id,所以现在您将如何使用album_id 进行第二次查询。如果对您有帮助,请点赞并接受我的回答。
猜你喜欢
  • 2022-08-17
  • 1970-01-01
  • 2011-01-26
  • 2021-12-14
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2014-08-18
相关资源
最近更新 更多