0

我使用 PDO 连接到 sqlite3,但由于某种原因我无法使外键工作。根据文档,这个“PRAGMA short_column_names=1”应该启用它。我这样做:

$con = new PDO('sqlite:z:/testing.db');
$res = $con->exec('PRAGMA foreign_keys=ON');
var_dump($res);die();

返回 0。我尝试使用外键创建实际表,但它不起作用。对 SQLite3 类的直接请求虽然有效:

$con = new SQLite3('z:/testing.db');
$con->exec('PRAGMA foreign_keys = ON;');
var_dump($con->query('PRAGMA foreign_keys;')->fetchArray());

这将返回数组(2){ [0]=> int(1) ["foreign_keys"]=> int(1) }

根据 SQLite3::version(),我有 sqlite 版本 3.7.7.1。我的 PHP 版本是 5.3.18,在 Windows 上运行。

请帮助我让它与 PDO 一起运行。谢谢!

4

1 回答 1

7

我不知道PRAGMA short_column_names=1;应该与 PDO 一起发布以便外键约束与 SQLite 一起使用的想法。但是,您也应该PRAGMA foreign_keys = ON;使用 PDO 发出问题。

试试这个:

<?php

// SQL for creating database structure
$databaseSql = <<<SQL
    CREATE TABLE `user` (
        `id` INTEGER PRIMARY KEY AUTOINCREMENT,
        `name` TEXT NOT NULL,
        UNIQUE( `name` )
    );

    CREATE TABLE `userProfile` (
        `userId` INTEGER NOT NULL CONSTRAINT `userProfile_userId` REFERENCES `user`( `id` ) ON UPDATE CASCADE ON DELETE CASCADE,
        `image` TEXT NOT NULL
    );
SQL;

// SQL for inserting dummy data
$dataSql = <<<SQL
    INSERT INTO `user` VALUES( 1, "John" );
    INSERT INTO `user` VALUES( 2, "Mary" );
    INSERT INTO `user` VALUES( 3, "Joe" );
    INSERT INTO `userProfile` VALUES( 1, "/images/john.jpg" );
    INSERT INTO `userProfile` VALUES( 2, "/images/mary.jpg" );
    INSERT INTO `userProfile` VALUES( 3, "/images/joe.jpg" );
SQL;

// create a temporary SQLite instance in memory
$db = new PDO( 'sqlite::memory:', null, null, array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false
) );

// activate use of foreign key constraints
$db->exec( 'PRAGMA foreign_keys = ON;' );

// create database
$db->exec( $databaseSql );
// insert dummy data
$db->exec( $dataSql );

// should dump 3 records
var_dump( $db->query( 'SELECT * FROM `userProfile`;' )->fetchAll() );

// delete 1 user, cascade deleting 1 userProfile as well
$db->exec( 'DELETE FROM `user` WHERE `id` = 1;' );

// should dump 2 records
var_dump( $db->query( 'SELECT * FROM `userProfile`;' )->fetchAll() );

它应该导致以下结果:

array(3) {
  [0]=>
  array(2) {
    ["userId"]=>
    string(1) "1"
    ["image"]=>
    string(16) "/images/john.jpg"
  }
  [1]=>
  array(2) {
    ["userId"]=>
    string(1) "2"
    ["image"]=>
    string(16) "/images/mary.jpg"
  }
  [2]=>
  array(2) {
    ["userId"]=>
    string(1) "3"
    ["image"]=>
    string(15) "/images/joe.jpg"
  }
}
array(2) {
  [0]=>
  array(2) {
    ["userId"]=>
    string(1) "2"
    ["image"]=>
    string(16) "/images/mary.jpg"
  }
  [1]=>
  array(2) {
    ["userId"]=>
    string(1) "3"
    ["image"]=>
    string(15) "/images/joe.jpg"
  }
}
于 2012-11-23T18:22:22.423 回答