簡體   English   中英

當我將數據插入子表中時,php / mysql CI沒有存儲父表的ID

[英]php/mysql CI when ever I insert data into child table it didnot store the id of parent table

我正在使用Codeignator框架,創建國家和城市類別。

我的桌子

CREATE TABLE country(
coun_id int(11) NOT NULL AUTO_INCREAMENT,
coun_name varchar(60),
child_id int(11),
PRIMARY KEY(coun_id)
);

CREATE TABLE city(
city_id int(11) NOT NULL AUTO_INCREAMENT,
city_name varchar(11),
coun_id int(11),
PRIMARY KEY(city_id),
FOREIGN KEY(coun_id) REFERENCE country(coun_id)
);

模型

$query = $this->db->where(['coun_name'=>$cat_country])->get('country');
if ( $query->num_rows() == 1){
    $data_city = array('city_name' =>$cat_city);
    $this->db->insert('city',$data_city);
}else{
    $data_con = array('coun_name'=>$cat_country);
    $this->db->insert('country',$data_con);
    $data_city = array('city_name' =>$cat_city);            
    $this->db->insert('city',$data_city);
}

假設找不到國家/地區輸出

國家表

coun_id || coun_name ||child_id ==> 
1       || Pakistan  || 0

城市表

city_id || city_name ||coun_id ==>
1       || Karachi   || 0

如何在城市表中獲取國家表的coun_id?

檢查以下代碼:

$query = $this->db->where(['coun_name'=>$cat_country])->get('country');
    if ( $query->num_rows() == 1){
        //get country data
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
        $coun_id = $data['coun_id']; //get country id 
        $data_city = array('city_name' =>$cat_city,'coun_id'=>$coun_id);
        $this->db->insert('city',$data_city);
    }else{
        $data_con = array('coun_name'=>$cat_country);
        $this->db->insert('country',$data_con);
        $insert_id = $this->db->insert_id();
        $data_city = array('city_name' =>$cat_city,'coun_id'=>$insert_id);  
        $this->db->insert('city',$data_city);
    } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM