如何同时插入数据父表和子表?

时间:2015-08-04 05:41:26

标签: php mysql codeigniter

我尝试使用codeIgniter框架将数据插入mysql,当我尝试它时会显示此错误

    Error Number: 1452

Cannot add or update a child row: a foreign key constraint fails (`pslsystem`.`invoice_description`, CONSTRAINT `invoice_description_ibfk_1` FOREIGN KEY (`reference_no`) REFERENCES `myinvoice` (`reference_no`) ON DELETE CASCADE ON UPDATE CASCADE)

INSERT INTO `invoice_description` (`reference_no`, `description`) VALUES (6, 'description1')

Filename: C:/xampp/htdocs/pslsystem/application/models/sample_model.php

Line Number: 21

这是我的两张桌子:

CREATE TABLE myinvoice (
    invoice_id INT  NOT NULL AUTO_INCREMENT,
    invoice_type  varchar(30) NOT NULL,
    reference_no varchar(30) NOT NULL UNIQUE,
    des_title varchar(300) NULL ,
    PRIMARY KEY (invoice_id, reference_no)

) ENGINE=InnoDB;

CREATE TABLE invoice_description(
 des_id INT NOT NULL AUTO_INCREMENT,
 reference_no varchar(30) NOT NULL,
 description varchar(300) NOT NULL,
 PRIMARY KEY (des_id,reference_no),
 FOREIGN KEY (reference_no) REFERENCES myinvoice (reference_no) on delete cascade ON UPDATE CASCADE
)ENGINE=InnoDB;

这是我的模特

function insert_entry($data1, $data2) {

    $this->db->insert('myinvoice', $data1);

    $data2['reference_no'] = $this->db->insert_id();

    $this->db->insert('invoice_description', $data2);
}

这是我的控制器:

if($this->form_validation->run())
        {
            $this->load->database();
            $this->load->model('sample_model');
            $data1 = array(
                  'invoice_type' => $this->input->post('type'),
                  'reference_no' => $this->input->post('ref'),
                  'des_title' => $this->input->post('title'),

                  );

        $data2 = array(
            'reference_no' => $this->input->post('ref'),
             'description' => $this->input->post('des'),
        );

             $this->sample_model->insert_entry($data1,$data2);



        }else{

            $this->load->view('sample_view');
        }

当我尝试插入只插入父表数据时。并解决这个错误。

1 个答案:

答案 0 :(得分:0)

您尝试将reference_no插入invoice_description两次 一旦你输入你的控制器代码

$data2 = array(
            'reference_no' => $this->input->post('ref'),
             'description' => $this->input->post('des'),
        );

在你的模特中排名第二

$this->db->insert('myinvoice', $data1);
$data2['reference_no'] = $this->db->insert_id();

只需删除

 $data2['reference_no'] = $this->db->insert_id();

这来自您的模型,因为最后插入的ID不是您的reference_no