更新包含外键时出错

时间:2014-04-29 13:52:00

标签: php mysql codeigniter

我在更新时出错 这是我的模特

public function edit_nilai(){   
    $id_nilai=$this->input->post('id_nilai');
    $id_mapel=$this->input->post('id_mapel');//foreign key
    $nilai=$this->input->post('nilai');
    $nisn=$this->input->post('nisn');//foreign key


    $data = array(
        'id_nilai'=>$id_nilai,
        'id_mapel'=>$id_mapel,
        'nilai'=>$nilai,
        'nisn'=>$nisn

    );
    $this->db->join('mapel', 'mapel.id_mapel=nilai.id_mapel');
    $this->db->where('nisn',$nisn);
    $this->db->update('nilai',$data);

}

这是我的控制器

function edit(){
    if($this->input->post('submit')){
        $this->m_nilai->edit_nilai();
        redirect('/admin/c_peserta'); 
    }
}

这是我收到的错误消息:

Cannot add or update a child row: a foreign key constraint fails (`ppdb`.`nilai`, CONSTRAINT `nilai_ibfk_1` FOREIGN KEY (`id_mapel`) REFERENCES `mapel` (`id_mapel`) ON DELETE CASCADE ON UPDATE CASCADE)

UPDATE `nilai` SET `id_nilai` = 0, `id_mapel` = 0, `nilai` = '6.00', `nisn` = '123456' WHERE `nisn` = '123456'

1 个答案:

答案 0 :(得分:0)

您可以尝试修改

$this->db->join('mapel', 'mapel.id_mapel=nilai.id_mapel');
$this->db->where('nisn',$nisn);
$this->db->update('nilai',$data);

$this->db->where('nisn',$nisn);
$this->db->update('mapel m join nilai n on m.id_mapel = n.id_mapel',$data);