Welcome Guest, Not a member yet? Register   Sign In
Multiple inserts and last insert id
#1

[eluser]Unknown[/eluser]
Does Codeigniter 2 have a cleaner way of doing what's shown in the code, below?

As you can see, I'm trying to insert data, via POST, into 3 separate tables that are related to each other.

Once I insert into table1, I want to grab its last insert id and enter that as the value for table2_id and table3_id (foreign key).

I've Googled this and this and people have mentioned db transactions but I was wondering if there's also a way without transactions.

Just curious, being a CI newbie.

Here's the code:
Code:
public function create()
    {
        $this->load->model('table1');
        $this->load->model('table2');
        $this->load->model('table3');

//validation goes here

        $id1   = $this->table1->insert($this->input->post('table1'));

        $data2 = array_merge($this->input->post('table2'), array('table1_id' => $id1));
        $id2   = $this->table2->insert($data2);

        $data3 = array_merge($this->input->post('table3'), array('table1_id' => $id1));
        $id3   = $this->table3->insert($data3);
    }

Thanks Smile




Theme © iAndrew 2016 - Forum software by © MyBB