问题描述
让我先解释表结构:
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| firstname | varchar(255) | NO | | NULL | |
| name | varchar(255) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
通过外键从另一个表中引用id字段。
The id field is referenced from another table through a foreign key.
说我在我的模型中有一个函数,如下:
Say I have a function in my model like this:
public function delete_user($id) {
return $this->db->delete('users', array('id' => $id));
}
当从另一个表引用此用户时,它应该会抛出一个错误。 坏的事情是,Codeigniter实际上在一个完整的页面上显示错误:
When this user is referenced from the other table, it should throw an error. The "bad" thing is, that Codeigniter actually shows that error on a full page:
Error Number: 1451
Cannot delete or update a parent row: a foreign key constraint fails (`testing`.`users_link`, CONSTRAINT `users_link_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
DELETE FROM `users` WHERE `id` = '1'
方法让delete_user函数返回FALSE,而不是显示错误?我想通知用户,他们必须先做其他事情。我尝试使用事务并返回transaction_status,但仍然会引发错误。
Is there a way to make the delete_user function return FALSE instead of showing the error? I'd like to notify the user that they have to do something else first. I tried using transactions and returning the transaction_status, but that still throws the error.
推荐答案
在config.php文件中找到行
in the config.php file find the line
$db['default']['db_debug']
并将其设置为FALSE。这将防止Codeigniter在屏幕上打印错误。
and set it to FALSE. This will prevent Codeigniter from printing the error on the screen.
也可以在删除功能中检查:
Also in the delete function you can check:
if ($this->db->_error_number() == 1451)
如果你在这种情况下需要做特别的事情。
If you need to do something special when this happens.
这篇关于Codeigniter外键约束检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!