我将使用SQLite help page中有关外键约束的示例:
让我们在SQLite中构建2个表:
CREATE TABLE artist(
artistid INTEGER PRIMARY KEY,
artistname TEXT
);
CREATE TABLE track(
trackid INTEGER PRIMARY KEY,
trackname TEXT,
trackartist INTEGER,
CONSTRAINT fk
FOREIGN KEY(trackartist) REFERENCES artist(artistid))
ON UPDATE CASCADE ON DELETE CASCADE
);
让我们从SQLite命令添加2条记录:
sqlite> pragma foreign_keys = ON;
sqlite> INSERT INTO artist(artistid, artistname) VALUES(null, 'Bing Crosby');
sqlite> INSERT INTO track(trackid, trackname, trackartist) VALUES(null, 'White Christmas', 1);
sqlite> SELECT * FROM artist;
1|Bing Crosby
sqlite> SELECT * FROM track;
1|White Christmas|1
现在,虽然命令工具 NOT 允许(正确)插入:
sqlite> INSERT INTO track(trackid, trackname, trackartist) VALUES(null, 'Another Track', 9);
Error: FOREIGN KEY constraint failed
另一方面php DOES 允许(错误)这个:
$dbh = new \PDO('sqlite:test.sq3');
$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
try {
if (!$dbh->beginTransaction())
throw new \Exception('Could not started a transaction!');
//$dbh->exec('PRAGMA foreign_keys = ON;');
$query = $dbh->prepare('PRAGMA foreign_keys = ON;');
$query->execute();
//$dbh->exec("INSERT INTO track(trackid, trackname, trackartist) VALUES(null, 'Another Track', 9);");
$query = $dbh->prepare("INSERT INTO track(trackid, trackname, trackartist) VALUES(null, 'White Christmas', 9);");
$query->execute();
$dbh->commit();
} catch (\Exception $e) {
$dbh->rollback();
}
查看违规行为:
sqlite> SELECT * FROM track;
1|White Christmas|1
2|Another Track|9
有什么想法吗?谢谢!