将数据插入两个表,一个依赖于另一个 [英] Insert data into two tables, one depend on another

查看:212
本文介绍了将数据插入两个表,一个依赖于另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我在数据库中有这样的结构:

For example I have such structure in database:

table1:
[id]
[content]

table1: [id] [content]

table2:
[id]
[table1_id]

table2: [id] [table1_id]

并且我想同时插入一些资料这两个表,但问题是与[table1_id],这是从table1的主键。如何插入它?

and I want insert some data at the same time into this two tables, but the problem is with [table1_id] which is primary key from table1. How can I insert it?

推荐答案

为了将表1的主键插入表2,帮助这个任务。

In order to insert the primary key of table 1 into table 2, code igniter has built in helper functions to help with this task.

//prepare data for table 1    
$data = array(
   'conent' => 'My content',
);
//insert into table 1
$this->db->insert('table1',$data);

//prepare data for table 2
$data = array(
   'table1_id' => $this->db->insert_id(),
);
//insert into table 2
$this->db->insert('table2',$data);

这篇关于将数据插入两个表,一个依赖于另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆