简体   繁体   English

如何在mysql中的两个表中插入数据-Laravel

[英]How to insert data into two tables in mysql - Laravel

I want to insert data into two tables of mysql, 我想将数据插入mysql的两个表中,

Tables are as follows: 表格如下:

1) t_entity_details 2) t_preferences 1)t_entity_details 2)t_preferences

Columns inside the table are as follows: 表格内的栏如下:

t_entity_details t_entity_details

- Entity_id (primary key, auto-increment)
- First_Name
- Sex
- TagLine
- Personal_Desc
- DOB
- Lang

t_preferences t_preferences

- Entity_id (primary key too, No auto-increment)
- other columns......

Now when I submit a form, the Entity_id should be same in both the tables. 现在,当我提交表单时,两个表中的Entity_id应该相同。 So how to do that? 那么该怎么做呢? Please help me with this. 请帮我解决一下这个。

The Solution is simple. 解决方法很简单。 You can use "mysql_insert_id" to get the last incremented/inserted id. 您可以使用“ mysql_insert_id”获取最后一个递增/插入的ID。 You can use that in turn to insert into your second table. 您可以依次使用它插入第二张表。

In Eloquent, things are even more simpler, Assuming you know about Eloquent Models,. 假设您了解Eloquent模型,在Eloquent中,事情将变得更加简单。 You insert to the first 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);

You can then get the last insert id as follows: 然后,您可以获取最后的插入ID,如下所示:

  $entity_id = $saveResult->id;

You use this to insert into the second table: 您可以使用它插入第二张表:

$insert_secondTable_array = array("Foo" => "bar");
$insert_secondTable_array['EntityId'] = $entity_id;
$result = SecondEloquentModel::create($insert_secondTable_array);

This inserts into both tables. 这将插入两个表中。

In this scenario do the query statement as, 在这种情况下,查询语句如下:

insert into t_entity_details (column1,column2,column3,...) VALUES (value1,value2,value3,...); 插入t_entity_details (column1,column2,column3,...)值(value1,value2,value3,...);

insert into t_preferences SELECT * FROM t_entity_details ; 插入到t_preferences中 SELECT * FROM t_entity_details ;

i believe this type will solve your problem if you don't do manipulation using other columns. 我相信如果您不使用其他列进行操作,则此类型将解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM