Codeigniter foreign key constraint check

爱⌒轻易说出口 提交于 2019-12-21 17:26:31

问题


Let me first explain the table structure:

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| firstname | varchar(255) | NO   |     | NULL    |                |
| name      | varchar(255) | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

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));
}

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'

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.


回答1:


in config folder database.php file find the line

$db['default']['db_debug']

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.




回答2:


I use it in this way Codeigniter 3.0

Model

/*
 * function to delete user
 */
function delete_user($id)
{
            if ( ! $this->db->delete('users', array('id' => $id)))
            {
                            return $this->db->error();
            }
    return FALSE;
}

Controller

$fk_check = $this->User_model->delete_user($id);

if($fk_check) {
// Unable to delete record
// $fk_check is an array containing $fk_check['code'] & $fk_check['message']
exit();
}

// Here your record has been deleted


来源:https://stackoverflow.com/questions/10463429/codeigniter-foreign-key-constraint-check

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!