【发布时间】:2019-11-12 01:33:31
【问题描述】:
为什么ON DELETE SET NULL通过应用程序代码删除行失败,但手动执行SQL语句时行为正确?
我有一个待办事项表和一个类别表。 todo 表有一个category_id 外键,它在类别表中引用id,它是使用“ON DELETE SET NULL”操作创建的。
create table `category` (
`id` integer not null primary key autoincrement,
`name` varchar(255) not null
);
create table `todo` (
`id` integer not null primary key autoincrement,
`title` varchar(255) not null,
`complete` boolean not null default '0',
`category_id` integer,
foreign key(`category_id`) references `category`(`id`) on delete SET NULL on update CASCADE
);
我的应用程序中还有一个端点,允许用户删除一个类别。
categoryRouter.delete('/:id', async (req, res) => {
const { id } = req.params
await req.context.models.Category.delete(id)
return res.status(204).json()
})
此路由成功删除了类别,但问题是相关的待办事项没有将其category_id 属性设置为空,因此它们最终得到一个不再存在的类别 id。奇怪的是,如果我打开我的数据库 GUI 并手动执行查询以删除一个类别...DELETE FROM category WHERE id=1...“ON DELETE SET NULL”钩子成功触发。任何具有category_id=1 的待办事项现在都设置为空。
完整的应用源码可以在here找到。
【问题讨论】:
-
您是否启用了外键支持? Enabling Foreign Key Support
标签: sql sqlite express knex.js objection.js