Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从一个查询向另一个查询添加值_Javascript_Node.js_Postgresql - Fatal编程技术网

Javascript 如何从一个查询向另一个查询添加值

Javascript 如何从一个查询向另一个查询添加值,javascript,node.js,postgresql,Javascript,Node.js,Postgresql,我正在使用React使用NodeJS将数据发送到我的PostgreSQL数据库。我的songs表中有一个外键,它引用了albums表中的id。我的问题是,如何将我的id从第一次插入返回到第二次插入的相册中?这是我目前的代码: const addData = (request, response) => { const uuid = uuidv4(); db.pool.query('INSERT INTO albums (title, date, description, id) VAL

我正在使用React使用NodeJS将数据发送到我的PostgreSQL数据库。我的songs表中有一个外键,它引用了albums表中的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 => {
      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));

}
我尚未将唱片集id添加到我的歌曲插入中。我正在等待如何将唱片id中的值输入到第二次插入中?

因为我在歌曲表中看不到唱片id列,所以我没有为此编写查询

您只需使用Album\u id将最后插入的id传递给下一个


查询后的console.log会立即将相册id记录到相册表中,是吗?请提供您的表结构我所做的是设置了let album_id;在所有查询之前,然后添加相册\u id=res.rows[0].id;在第一次查询之后,然后在第二次查询中设置相册id。你的代码帮助了我。让我知道我是否应该在我的代码中做任何调整。关于代码中的更改,根据我的回答,现在您可以获得album_id,因此现在取决于您如何使用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));

}