我想给用户一个选项,当他在父表中删除一个项目时,要么级联删除,要么给引用外键的子表中的项目设置null,这在sqlite中是可能的吗?或者我必须在我的代码中这样做?这些是我当前在创建两个表时使用的命令,当前在删除一个类别时,分配给这个类别的项被设置为null,基本上我想给用户一个选项来删除所有这些项,最好是在sql代码中。
await database.execute(
"CREATE TABLE $TABLE_CATEGORIES ("
"$COLUMN_CATEGORYID INTEGER PRIMARY KEY,"
"$COLUMN_CATEGORYNAME TEXT"
")",
);
await database.execute(
"CREATE TABLE $TABLE_GROCERIES ("
"$COLUMN_ID INTEGER PRIMARY KEY,"
"$COLUMN_NAME TEXT,"
"$COLUMN_PPU REAL,"
"$COLUMN_BASE REAL,"
"$COLUMN_STOCK REAL,"
"$COLUMN_CATEGORYID INTEGER,"
"FOREIGN KEY($COLUMN_CATEGORYID) REFERENCES $TABLE_CATEGORIES($COLUMN_CATEGORYID) ON DELETE SET NULL"
")",
);
1条答案
按热度按时间zzwlnbp81#
你需要在代码中解决这个问题。您只能将数据库配置为“set null”或“cascade delete”。如果这是我的任务,我将使用“on delete set null”,并允许用户通过触发第二个sql查询来删除子行,如
DELETE FROM child_table WHERE parent_id = $parentid