Laravel - multi-insert rows and retrieve ids

前端 未结 2 1937
庸人自扰
庸人自扰 2021-01-02 10:00

I\'m using Laravel 4, and I need to insert some rows into a MySQL table, and I need to get their inserted IDs back.

For a single row, I can use ->insertGetI

2条回答
  •  再見小時候
    2021-01-02 10:10

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

    According to Schema api insertGetId() accepts array

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

    So you have to be able to do

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

    Thats speaking, if using MySQL, you could retrive the first id by this and calculate the rest. There is also a DB::getPdo()->lastInsertId(); function, that could help.

    Or if it returened the last id with some of this methods, you can calculate it back to the first inserted too.

    EDIT

    According to comments, my suggestions may be wrong.

    Regarding the question of 'what if row is inserted by another user inbetween', it depends on the store engine. If engine with table level locking (MyISAM, MEMORY, and MERGE) is used, then the question is irrevelant, since thete cannot be two simultaneous writes to the table.

    If row-level locking engine is used (InnoDB), then, another possibility might be to just insert the data, and then retrieve all the rows by some known field with whereIn() method, or figure out the table level locking.

提交回复
热议问题