FMDB 在自引用键上级联

FMDB cascade on self referenced key

我已经使用以下语句创建了一个 SQLite 数据库:

"CREATE TABLE Projects (Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, productsIds TEXT, title TEXT, parentId INTEGER, FOREIGN KEY(parentId) REFERENCES Projects(Id) ON DELETE CASCADE ON UPDATE NO ACTION);"

如您所见,每个项目可能有 0 个或多个子项目。

我想删除所有子项目(以及子项目的子项目,等等)如果我删除了父项目,但我删除了一个父子项目没有被删除。

插入行:

INSERT INTO Projects (id,productsIds,title,parentId) VALUES (?,?,?,?)

删除行:

DELETE FROM Projects WHERE id = 2

我正在使用 FMDB。

你能帮忙吗

谢谢

您的问题可能是尚未启用 FOREIGN KEY 支持。为此,您可能需要 issue/run

pragma foreign_keys = ON;

根据 :-

2. Enabling Foreign Key Support

In order to use foreign key constraints in SQLite, the library must be compiled with neither SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined. If SQLITE_OMIT_TRIGGER is defined but SQLITE_OMIT_FOREIGN_KEY is not, then SQLite behaves as it did prior to version 3.6.19 (2009-10-14) - foreign key definitions are parsed and may be queried using PRAGMA foreign_key_list, but foreign key constraints are not enforced. The PRAGMA foreign_keys command is a no-op in this configuration. If OMIT_FOREIGN_KEY is defined, then foreign key definitions cannot even be parsed (attempting to specify a foreign key definition is a syntax error).

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection. (Note, however, that future releases of SQLite might change so that foreign key constraints enabled by default. Careful developers will not make any assumptions about whether or not foreign keys are enabled by default but will instead enable or disable them as necessary.) The application can also use a PRAGMA foreign_keys statement to determine if foreign keys are currently enabled. The following command-line session demonstrates this:

sqlite> PRAGMA foreign_keys;
0
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys;
1
sqlite> PRAGMA foreign_keys = OFF;
sqlite> PRAGMA foreign_keys;
0

Tip: If the command "PRAGMA foreign_keys" returns no data instead of a single row containing "0" or "1", then the version of SQLite you are using does not support foreign keys (either because it is older than 3.6.19 or because it was compiled with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined).

It is not possible to enable or disable foreign key constraints in the middle of a multi-statement transaction (when SQLite is not in autocommit mode). Attempting to do so does not return an error; it simply has no effect.

SQLite Foreign Key Support