Laravel - multiline strings and return identifiers

I am using Laravel 4, and I need to insert some rows into the MySQL table, and I need to return their inserted identifiers.

For one line, I can use ->insertGetId() , however it does not support multiple lines. If I could at least extract the identifier of the first row, as normal MySQL does, it would be enough to figure out the others. Any ideas?

+6
source share
2 answers

As user Xrymz suggested, DB::raw('LAST_INSERT_ID();') returns the first.

According to api scheme insertGetId() accepts an array

public int insertGetId(array $values, string $sequence = null)

So you should be able to do

DB::table('table')->insertGetId($arrayValues);

Saying if you are using MySQL, you can extract the first id and calculate the rest. There is also a function DB::getPdo()->lastInsertId(); which may help.

Or, if he returned the last identifier using some of these methods, you can also calculate it back to the first.

EDIT

According to the comments, my suggestions may be wrong.

Regarding the question of what, if a row is inserted by another user between them, it depends on the storage mechanism. If you use a table-level locking mechanism (MyISAM, MEMORY, and MERGE), the question does not matter, because it cannot have two simultaneous entries in the table.

If the row-level locking mechanism (InnoDB) is used, then another option would be to simply insert the data and then retrieve all the rows with some known field using the whereIn() method or define table-level locking .

+1
source

This is the behavior of mysql last-insert-id

Important
If you insert multiple rows with the same INSERT statement, LAST_INSERT_ID () returns the value generated only for the first inserted row. The reason for this is to make it easy to play the same INSERT statement against any other server.

u can try to use many insert elements and take them ids or after saving try using $ data-> id which should be the last inserted id.

+3
source

Source: https://habr.com/ru/post/973184/


All Articles