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 is a way without transactions.
Just curious, being a CodeIgniter newbie.
Here's the 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);
}
You have the function:
$this->db->insert_id();
that it can be used after the insert and gives you the id of the inserted data. You can always add an if else statement to check that you have inserted the data correctly and carry on with the rest of the inserts.