我正在使用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的价值?
答案 0 :(得分:1)
由于我在歌曲表中看不到album_id
列,因此我没有为此编写查询。
您只需要使用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));
}