我是 postgreSQL 新手,我试图从表中删除一行,然后从另一个表和链接表中删除相关数据;我一边努力学习一边这样做,我很确定我所做的事情是错误的。
它给了我一个错误:
update or delete on table "users" violates foreign key constraint "usertopantry_user_id_fkey" on table "usertopantry"
userstoppantry 桌子看起来像:
user_id : integer : NOT NULL true : Primary KEY: true DEFAULT nextval('usertopantry_user_id_seq'::regclass)
pantry_id: integer : NOT NULL true : Primary KEY: true DEFAULT
nextval('usertopantry_pantry_id_seq'::regclass)
这是我运行的代码,当用户删除用户时尝试从所有源中删除:
const deleteUser = (request, response) => {
const id = parseInt(request.params.id)
pool.query('DELETE FROM users WHERE user_id = $1', [id], (error, userResults) => {
if (error) {
throw error
}
if(response) {
pool.query('SELECT pantry_id FROM userstopantry WHERE user_id = $1', [id], (error, pantryResults) => {
if (error) {
throw error
}
pool.query('DELETE FROM pantries WHERE pantry_id = $1', [pantryResults.rows[0].pantry_id], (error, deletionResults) => {
if (error) {
throw error
}
pool.query('DELETE FROM userstopantry WHERE user_id = $1', [id], (error, results) => {
if (error) {
throw error
}
response.status(200).send(`User deleted with ID: ${id}`)
})
})
})
}
})
}
我正在使用 Node.js 和 pg.pool
我相信 DELETE CASCASE 正是您正在寻找的。它将自动删除其他表中的相关行。
这是一篇很好的第一篇文章https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-delete-cascade/