How to handle exception that can not delete because it is a foreign key

5

I can not handle an exception that happens when I delete an address that is being used in another table. I'm using codeigniter

My code is:

public function delete_endereco($cod_clientes_endereco){
    try{
        $acao = $this->db->delete('clientes_enderecos', array('cod_clientes_endereco' => $cod_clientes_endereco));
    }
    catch (SqlException $ex) {
        SqlException::throwDeleteException($ex);
    }
    if($acao){
        $this->session->set_flashdata('success', 'Endereço deletado com sucesso!');
    }
    else{
        $this->session->set_flashdata('error', 'Este endereço não pode ser deletado, pois existe um pedido utilizando ele.');
    }
    redirect("pagina_cliente?page=enderecos");
}

The following error appears:

A Database Error Occurred

Error Number: 1451

Cannot delete or update a parent row: a foreign key constraint fails ('db'.'pedidos', CONSTRAINT 'fk_pedidos_clientes_enderecos1' FOREIGN KEY ('endereco_cobranca') REFERENCES 'clientes_enderecos' ('cod_clientes_endereco') ON DELETE NO ACTION ON UPDATE NO ACTIO)

DELETE FROM 'clientes_enderecos' WHERE 'cod_clientes_endereco' = '5'

Filename: controllers/Pagina_cliente.php

Line Number: 160
    
asked by anonymous 27.10.2015 / 16:28

2 answers

2

Hi. This is because codeigniter does not throw an exception in this case.

What you can do is:

Open the file database.php, find the line $db['default']['db_debug'] and seven a FALSE .

And in your code you can keep the following if:

if ($this->db->_error_number() == 1451)

If you need something special to happen in case the error is thrown by db. I believe this should work.

    
27.10.2015 / 17:08
1

To solve this problem I created a column in my address table called "active", and then instead of doing the delete operation on the address, I just update the "active" column to zero.

In the list of all addresses for the user to see, I just ready the addresses that have the "active" column equal to 1.

Thanks to everyone who tried to help me ...

    
28.10.2015 / 11:42