我使用 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 执行此操作时,我没有收到有关外键约束的错误,并且该类别被删除。以下是我的交易和类别模型。
事务.php:
class Transaction extends AppModel {
public $belongsTo = array('Location', 'TransactionType', 'Category', 'Account');
....
类别.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'));
}
}
我认为我的关联设置得很好,因为检索数据没有问题。但是,删除时不遵守外键。
我怀疑这与每次 CakePHP 连接到数据库时都必须运行“PRAGMA foreign_keys=ON”有关,但我不知道该怎么做。或者我的模型定义和关联可能有问题。
我使用的是 CakePHP 2.3.5 版和 Sqlite3 3.7.13 版。
任何帮助将不胜感激!谢谢 :)