简体   繁体   中英

Cannot add or update a child row: a foreign key constraint fails Error

My code is:

private function get_parameters_to_array()
{
    $data = array(
        'datahora' => $this->input->post('datahora'),
        'valor' => $this->input->post('valor'),
        'idProduto' => $this->input->post('idProduto'),
        'idFuncionario' => $this->input->post('idFuncionario'),
        'idMesa' => $this->input->post('idMesa')
    );
    return $data;
}

I need to convert the 3 ID values to Int, how to do that? The error I'm getting is this one:

Error Number: 1452

Cannot add or update a child row: a foreign key constraint fails ( tucunaredb . pedido , CONSTRAINT fk_Pedido_Funcionario1 FOREIGN KEY ( idFuncionario ) REFERENCES funcionario ( id ) ON DELETE NO ACTION ON UPDATE NO ACTION)

INSERT INTO Pedido ( datahora , valor , idProduto , idFuncionario , idMesa , ativo ) VALUES ('2016-02-24 23:14:16', '6.50', '8', '5', '2', 1)

It's simple and it's exactly what's the error saying: the value you're trying to insert into the column idFuncionario which has a foreign key to funcionario.id is wrong. You probably don't have any record with id 5 in the parent table funcionario .

You have to create such record first, then you can reference it from other tables.

The point of foreign keys is to maintain the referential integrity , in other words, data consistency .

You have the foreign key fk_Pedido_Funcionario1 on the column Pedido.idFuncionario which references to the column funcionario.id . That means you can't have a different value in the Pedido.idFuncionario than are values in the funcionario.id and the database is checking that. When you're trying to insert a different value, it throws the error you got.

The only other allowed value is NULL , but only in a case column can contain such value (is not defined with NOT NULL ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM