Codeigniter 2:多次插入和最后插入 ID
Codeigniter 2 是否有更简洁的方法来执行下面代码中所示的操作?
正如您所看到的,我尝试通过 POST 将数据插入到 3 个彼此相关的单独表中。
插入 table1
后,我想获取其最后插入 id
并将其输入为 table2_id
和 table3_id
的值代码>(外键)。
我用谷歌搜索了这个和这个,人们提到了数据库事务,但我想知道是否有一种没有事务的方法。
只是好奇,作为一个 CodeIgniter 新手。
代码如下:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您拥有以下功能:
可以在插入后使用它并为您提供插入数据的 id。您始终可以添加 if else 语句来检查是否已正确插入数据并继续执行其余插入操作。
You have the function:
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.