我使用PRAGMA foreign_keys = ON在SQLITE中启用了外键;并确认它在下面工作。
sqlite> PRAGMA foreign_keys = ON;
sqlite> CREATE TABLE transactions (
...> id integer primary key,
...> amount REAL,
...> item TEXT,
...> created DATETIME,
...> modified DATETIME,
...> date DATE,
...> time TIME,
...> description TEXT,
...> transaction_type_id INTEGER,
...> category_id INTEGER,
...> account_id INTEGER,
...> location_id INTEGER,
...> FOREIGN KEY (transaction_type_id) REFERENCES transaction_types(id),
...> FOREIGN KEY (category_id) REFERENCES categories(id),
...> FOREIGN KEY (account_id) REFERENCES accounts(id),
...> FOREIGN KEY (location_id) REFERENCES locations(id)
...> );
sqlite> INSERT INTO transactions VALUES (null, '5.0', 'test', '2013-06-11 18:33:56', '2013-06-11 18:33:56', '2013-06-11', '18:33:00', 'test description', 2, 1, 2, 1);
sqlite> SELECT * FROM categories;
1|fsfs|2013-06-11 18:33:38|2013-06-11 18:33:38
sqlite> SELECT * FROM transactions JOIN categories ON transactions.category_id=categories.id;
4|5.0|test|2013-06-11 18:33:56|2013-06-11 18:33:56|2013-06-11|18:33:00|test description|2|1|2|1|1|fsfs|2013-06-11 18:33:38|2013-06-11 18:33:38
sqlite> DELETE FROM categories WHERE id=1;
Error: foreign key constraint failed
sqlite>
但是,当我尝试通过CakePHP执行此操作时,我没有获得有关外键约束的错误,并且该类别已被删除。以下是我的交易和类别模型。
Transaction.php:
class Transaction extends AppModel {
public $belongsTo = array('Location', 'TransactionType', 'Category', 'Account');
....
Category.php:
class Category extends AppModel {
public $hasMany = array('Transaction', 'Budget');
....
我在CategoriesController.php中对Category的删除功能是通过组件功能完成的,它们如下所示。
CategoriesController.php - >删除
public function delete($id) {
$this->Crud->delete($this, $id, "Category");
}
CrudComponent.php - >删除
public function delete($current, $id, $modelName) {
$className = strtolower(Inflector::humanize($modelName));
if ($current->request->is('get')) {
throw new MethodNotAllowedException();
}
if ($current->$modelName->delete($id)) {
$current->Session->setFlash('The '.$className.' with id: ' . $id . ' has been deleted.');
$current->redirect(array('action' => 'index'));
}
}
我认为我的关联设置得很好,因为我没有检索数据的问题。但是,删除时不遵守外键。
我怀疑这与必须运行" PRAGMA foreign_keys = ON"每次CakePHP连接到数据库,但我不知道如何做到这一点。或者我的模型定义和关联可能有问题。
我使用CakePHP版本2.3.5和Sqlite3版本3.7.13。
任何帮助将不胜感激! 谢谢:))