[英]Inserting data into multiple tables with foreign key using CodeIgniter framework
我嘗試使用CodeIgniter將數據插入具有外鍵的多個表中。
這是我的第一張桌子koor_pen
no_koor( 主要 )| utm_y | utm_x | latit | 隆吉
這是我的第二個表,名為input_pen
no_form( 主要 )| kode_bps | no_obs | no_koor( 外國 )| t_tanah | 卡他坦
這是我的控制器
function c_submit(){
$data = array(
'no_form' => $this->input->post('noform'),
'kode_bps' => $this->input->post('kodebps'),
'no_obs' => $this->input->post('noobs'),
'no_koor' => $this->input->post('nokoor'),
'tanaman_u' => $this->input->post('tutama'),
't_tanah' => $this->input->post('ttanah'),
'catatan' => $this->input->post('cat')
);
$datakoor = array(
'no_koor' => $this->input->post('nokoor'),
'utm_y' => $this->input->post('y'),
'utm_x' => $this->input->post('x'),
'latit' => $this->input->post('deg')." ".
$this->input->post('min')." ".
$this->input->post('sec'),
'longi' => $this->input->post('deg2')." ".
$this->input->post('min2')." ".
$this->input->post('sec2')
);
$no_obs = $this->session->userdata('no_obs');
$this->m_input->m_submit($data, $datakoor);
redirect(base_url("c_input"));
}
和模型
function m_submit($data, $datakoor) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
$this->db->where('no_koor',$no_koor);
$this->db->insert('input_pen', $data);
$this->db->trans_complete();
return $this->db->insert_id();
}
您的值將為空。 您必須在$data
傳遞$no_koor
,以便可以替換該值。 嘗試這個:
function m_submit($data, $datakoor) {
$this->db->trans_start();
$this->db->insert('koor_pen', $datakoor);
$no_koor = $this->db->insert_id();
//$this->db->where('no_koor',$no_koor);
$data['no_koor'] = $no_koor;
$this->db->insert('input_pen', $data);
$this->db->trans_complete();
return $this->db->insert_id();
}
問題在這里no_koor(外來),這是您的外鍵,在您的查詢no_koor中,當您發送圖像時,此字段在查詢中獲得“”。 因此,請先檢查您的查詢。
該錯誤與圖像中顯示的foreign key constraint
有關。 規則是,您只能在parent
表中已經存在的child
表中添加或更新值。 因此,在插入時,請確保您要在child
表中插入的值已經存在於parent
表中。
有時插入順序也很重要,可能值是它們在查詢中的,但是您首先運行子表查詢。 因此,在這種情況下,請檢查訂單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.