How to insert data into two tables in mysql - Laravel - mysql

I want to insert data into two tables of mysql,
Tables are as follows:
1) t_entity_details
2) t_preferences
Columns inside the table are as follows:
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......
Now when I submit a form, the Entity_id should be same in both the tables. 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. 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,. 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:
$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,...);
insert into t_preferences SELECT * FROM t_entity_details;
i believe this type will solve your problem if you don't do manipulation using other columns.

Related

How to insert row number in database in Laravel

I am trying to insert ROW NUMBER inside table through controller but failed,
I have tried something like this but showing error,
$data = array(
'name'=>$request->name, 'email'=>$request->email, 'password'=>$password, 'status'=>1, 'user_id' =>ROW_NUMBER()
);
I just want to insert ROW NUMBER of table inside user_id.
Also, if not possible can we insert unique serial number inside user_id
Please help me out.
Each row has a column with name 'id' that is unique and Auto increment.
You can pass 'id' value to 'user_id' like below: (but it's not a good idea)
Why it is a bad idea?
Because when you delete your last row (assume id is 5) your next record 'id' is 6 but the user_id that will you retrieve with code below will be 5.
So, use the alternate option that I will give you in the following.
$last_user = User::orderBy('created_at', 'desc')->first();
$new_user = new User;
...
$new_user->user_id = $last_user->id + 1 ;
$new_user->save();
I figure it out from comments that you need a unique id and this your idea to solve this problem.
I have a better idea and hope that will help you.
you can use uniqid() method.
$new_user = new User;
...
$new_user->user_id = uniqid();
$new_user->save();

Insert foreign key into table

I have two tables.
basically i want to insert an id and a string into a table
However, id is a foreign key to another table in which customerId is the primary key
Furthermore my parent table has name
What i have, is name and the stringthat i get from a web ui. However, since i dont have the id that match the customerid of name in the parent table, i don't know how to insert it.
i got this so far, which by the way is my silly attempt to work my human logic around this issue:
INSERT INTO `PostDb`(`Offer`)
VALUES ("String") AND PostDb.id
WHERE CustomerDb.id = PostDb.id AND CustomerDb.name = "MyNameThatIHave"
What would work though. is that i do the following:
SELECT PostDb.id
FROM `PostDb` JOIN CustomerDb
WHERE `CustomerId` = CustomerDb.id AND CustomerDb.name = "MyNameThatIHave"
And then use the id that i get in a new insert command like this:
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
VALUES ("THE ID I GOT BEFORE","STRING")
Basically i want to achieve in ONE query, what the two before stated queries does
You can use SELECT to get values for insert:
INSERT INTO `PostDb`(`Offer`, customerid)
SELECT 'Whatever', id FROM customerdb
WHERE name = 'MyNameThatIHave'
Have you tried LAST_INSERT_ID() function which gives you the last inserted ID PK provided that ID is an auto_increment column.
Once you get that, then you can insert in your child table in your FK column along with the rest attributes.
In that case, use a INSERT INTO .. SELECT FROM construct like
INSERT INTO `PostDb`(`CustomerId`, `Offer`)
SELECT PostDb.`CustomerId`, 'Some Value'
FROM `PostDb` JOIN CustomerDb
ON `PostDb`.`CustomerId` = CustomerDb.id
WHERE CustomerDb.name = "MyNameThatIHave";

Insert multiple rows into two tables using autoincrement Mysql

I am trying to insert multiple rows into two tables connected by a foreign key that is autoincrement. I can't seem to find a good solution.
Tables:
eav_attribute_option
option_id (PK, Autoincrement)
attribute_id
sort_order
eav_attribute_option_value
value_id (PK, Autoincrement)
option_id (FK)
store_id
value
I want to do this:
insert into eav_attribute_option(attribute_id) values(100,101,102,103,...);
insert into eav_attribute_option_value(option_id,store_id,value) values
(1,0,"English"),(1,1,"German"),(2,0,"English1"),(2,1,"German2")
What would be the best approach to this, I can't seem to find a good one. :
Get next autoincrement then insert with it (need to lock table between)
Insert first part, then retreive PK values, build second part and insert (data incomplete for some time, what happens on error in second part?)
Some way to insert with join if it's possible?
Edit:
Just to clarify, I am looking to use the least amount of queries possible. I know I can do last inserted id, but I don't want to kill the server with thousands of inserts.
You can try something like this:
insert into eav_attribute_option (attribute_id) values(100);
insert into eav_attribute_option_value (option_id, store_id, value)
values (LAST_INSERT_ID(), 0, "English");
But you will need to insert the rows one by one. Consider doing a loop in your application.
$count = count('Count post value'); // $_POST value count
for($a=0;$a<$count;$a++)
{
$insert = 'insert into eav_attribute_option(attribute_id,sort_order) values (value1,value2)';
mysql_query($insert);
$insert_id = mysql_insert_id();
$insert2 = 'insert into eav_attribute_option_value(option_id,store_id,value) values
($insert_id,0,"English")';
mysql_query($insert2);
}

First wpdb insert to mySql new table isn't working

I created a new mySql table and I need the first field to be an index and a key.
I'm not sure I got the terminology right but I simply need that field to automatically increment by 1 with each insert.
So I defined that field as an index and gave it the auto_increment attribute.
Now I try to insert the first row like this:
$wpdb->insert('wp_branches', array(user_id=>$user_id, branchName=>$bname));
The index/key field branchId is missing from this query because I'm counting on the db to automatically give it the value 1 since it's the first insert, and then increment it with every additional insert.
For some reason the row isn't being inserted and db is left empty.
What am I doing wrong?
try like so:
$sql = $wpdb->prepare(
"INSERT INTO `wp_branches` (`user_id`,`branchName`) values (%d,%s)",
$user_id, $bname);
$wpdb->query($sql);
this will protect you against "injections" too.
modified so:
$wpdb->insert('wp_branches', array('user_id' => $user_id, 'branchName' => $bname));

Update multiple rows with known keys without inserting new rows if nonexistent keys are found

Let's imagine that we have table items...
table: items
item_id INT PRIMARY AUTO_INCREMENT
title VARCHAR(255)
views INT
Let's imagine that it is filled with something like
(1, item-1, 10),
(2, item-2, 10),
(3, item-3, 15)
I want to make multi update view for this items from data taken from this array [item_id] => [views]
'1' => '50',
'2' => '60',
'3' => '70',
'5' => '10'
IMPORTANT! Please note that we have item_id=5 in array, but we don't have item_id=5 in database.
I can use INSERT ... ON DUPLICATE KEY UPDATE, but this way image_id=5 will be inserted into talbe items. How to avoid inserting new key? I just want item_id=5 be skipped because it is not in table.
Of course, before execution I can select existing keys from items table; then compare with keys in array; delete nonexistent keys and perform INSERT ... ON DUPLICATE KEY UPDATE. But maybe there is some more elegant solutions?
Thank you.
You may try to generate a table of literals and update items by joining with the table:
UPDATE items
JOIN (SELECT 1 as item_id, 50 as views
UNION ALL
SELECT 2 as item_id, 60 as views
UNION ALL
SELECT 3 as item_id, 70 as views
UNION ALL
SELECT 5 as item_id, 10 as views
) as updates
USING(item_id)
SET items.views = updates.views;