Handling foreign key errors in Codeigniter

0

I'm implementing a code where you have a foreign key in two tables. I have already tried different media and can not handle the error:

Error Number: 1451

Cannot delete or update a parent row: a foreign key constraint fails ('base'.'tableus', CONSTRAINT 'doctor_ibfk_1' FOREIGN KEY ('department_id') REFERENCES 'department' ('department_id'))

DELETE FROM 'department' WHERE 'department_id' = '1'

Filename: models/Crud.php

Line Number: 292

I've used an example that I found Here and did not resolve it.

I'm reviewing my question here, let me pass on one important detail, I do not want the user to delete the data from the 'parent' table while having 'daughters' tables attached to it. Every time the user tries to do this he should get an error, in case I can not manage to handle this error in codeigniter.

    function delete_department($department_id)
{
  //verifica se recebe mensagem de erro na exclusão.

    $verifica_erro = $this->db->_error_number() == 1451;
    if ($this->delete_department($department_id) == $verifica_erro){
        echo "Mensagem de erro para o usuário!";
    }else{ 

 //senão tiver executa a exclusão.
        $this->db->where('department_id',$department_id);
        $this->db->delete('department');
    }
}

This code executes and after another error:

  

Fatal error: Uncaught TypeError: Argument 1 passed to CI_Exceptions :: show_exception () must be an instance of Exception, instance of Error given, called in /Path/system/core/Common.php on line 658 and defined in / Path / system / core / Exceptions.php: 190 Stack trace: # 0 /Path/system/core/Common.php(658): CI_Exceptions-> show_exception (Object (Error)) # 1 [internal function]: _exception_handler ( Object (Error)) # 2 {main} thrown in /Path/system/core/Exceptions.php online 190

    
asked by anonymous 09.02.2017 / 22:32

3 answers

1

After editing, the question became clearer, and the answer is simple: You can not handle this error any way you want . The way you make the error is already being addressed .

Think: There is an FK , and she is doing her job. So if you try to delete or update a parent record without using CASCADE , you will get the error in> PHP , because it happens in the bank, and CodeIgniter has no way to prevent errors from happening in the database. At most he'll give you a warning when they do, and that's what he's doing.

But , you can test the records before executing the delete attempt , and this is simple:

Consider that parent is your main table, and that child is your table that has parent_id related.

function delete($id = NULL){
        $query = "DELETE FROM parent WHERE id = '$id';";
        # The cat's leap: teste as tabelas antes de tentar excluir o principal
        $this->db->where('parent_id', $id);
        $test = $this->db->get('child');
        if(empty($test->result_array())){
            echo 'execute $query';
            //$this->db->query($query);
        } 
        else {
            echo 'show some error';
        }
}

That's all because you do not want to use CASCADE .

    
10.02.2017 / 14:05
3

This is a problem with your bank setup. Modeling is something important to avoid these things. This is to know the documentation of the application.

MySQL does this to prevent data integrity from being compromised, ie to prevent you from changing a primary record and making all other references to this record lost. See the MySQL documentation says (in a free translation) :

  

When an UPDATE or DELETE operation affects a key value in the parent table that has matching rows in the child table, the result depends on the referential action specified by using the ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. MySQL supports five options on the action to take, listed here:

Basically, you have to tell the database to automatically remove / update the child tables from the deleted / updated records in the main table. For this you should use CASCADE , as we saw above:

  

CASCADE: Delete or update the parent table row and automatically delete or update the corresponding rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, do not define multiple ON UPDATE CASCADE clauses that act on the same column in the parent table or in the child table.

An example of a referral auto-delete relationship

CREATE TABLE parent (
    id INT NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id INT,
    parent_id INT,
    INDEX par_ind (parent_id),
    FOREIGN KEY (parent_id)
        REFERENCES parent(id)
        ON DELETE CASCADE
        ON UPDATE CASCADE
) ENGINE=INNODB;

Viewed ON DELETE CASCADE and ON UPDATE CASCADE ? Yeah. This setting in the table avoids this error that you are seeing. So when id is changed / deleted in the parent table, parent_id will be automatically changed and deleted in the child tables.

Warning: Using CASCADE is a good habit to make copies of the records before deleting / updating. Thus, if necessary, it will be possible to retrieve the data for conference.

    
10.02.2017 / 00:51
1

You first have to delete the other table record from which this table is referencing through the foreign key.

    
09.02.2017 / 22:58