如何向 mysql - Laravel 中的两个表中插入数据
How to insert data into two tables in mysql - Laravel
我想向mysql、
的两个table中插入数据
表格如下:
1) t_entity_details
2) t_preferences
table内的栏目如下:
t_entity_details
- Entity_id (primary key, auto-increment)
- First_Name
- Sex
- TagLine
- Personal_Desc
- DOB
- Lang
t_preferences
- Entity_id (primary key too, No auto-increment)
- other columns......
现在,当我提交表单时,两个 table 中的 Entity_id 应该相同。那么该怎么做呢?
请帮我解决这个问题。
在这种情况下,查询语句为,
插入 t_entity_details(第 1 列、第 2 列、第 3 列...)
值(值 1、值 2、值 3、...);
插入 t_preferences SELECT * FROM t_entity_details;
如果您不使用其他列进行操作,我相信这种类型会解决您的问题。
解决方法很简单。您可以使用 "mysql_insert_id" 获取最后的 incremented/inserted id。您可以依次使用它插入第二个 table.
在Eloquent中,事情就更简单了,假设你知道Eloquent模型,。你插入到第一个 table:
$insertArray = array('First_Name' => 'Some_value',
'Sex' => 'Some_value',
'TagLine' => 'Some_value',
'Personal_Desc' => 'Some_value',
'DOB' => 'Some_value',
'Lang' => 'Some_value');
$saveResult = EloquentModel::create($insertArray);
然后你可以得到最后插入的id如下:
$entity_id = $saveResult->id;
你用这个插入第二个table:
$insert_secondTable_array = array("Foo" => "bar");
$insert_secondTable_array['EntityId'] = $entity_id;
$result = SecondEloquentModel::create($insert_secondTable_array);
这会插入到两个 table 中。
我想向mysql、
的两个table中插入数据表格如下:
1) t_entity_details 2) t_preferences
table内的栏目如下:
t_entity_details
- Entity_id (primary key, auto-increment)
- First_Name
- Sex
- TagLine
- Personal_Desc
- DOB
- Lang
t_preferences
- Entity_id (primary key too, No auto-increment)
- other columns......
现在,当我提交表单时,两个 table 中的 Entity_id 应该相同。那么该怎么做呢? 请帮我解决这个问题。
在这种情况下,查询语句为,
插入 t_entity_details(第 1 列、第 2 列、第 3 列...) 值(值 1、值 2、值 3、...);
插入 t_preferences SELECT * FROM t_entity_details;
如果您不使用其他列进行操作,我相信这种类型会解决您的问题。
解决方法很简单。您可以使用 "mysql_insert_id" 获取最后的 incremented/inserted id。您可以依次使用它插入第二个 table.
在Eloquent中,事情就更简单了,假设你知道Eloquent模型,。你插入到第一个 table:
$insertArray = array('First_Name' => 'Some_value',
'Sex' => 'Some_value',
'TagLine' => 'Some_value',
'Personal_Desc' => 'Some_value',
'DOB' => 'Some_value',
'Lang' => 'Some_value');
$saveResult = EloquentModel::create($insertArray);
然后你可以得到最后插入的id如下:
$entity_id = $saveResult->id;
你用这个插入第二个table:
$insert_secondTable_array = array("Foo" => "bar");
$insert_secondTable_array['EntityId'] = $entity_id;
$result = SecondEloquentModel::create($insert_secondTable_array);
这会插入到两个 table 中。