Laravel-多插入行并检索ID [英] Laravel - multi-insert rows and retrieve ids

查看:100
本文介绍了Laravel-多插入行并检索ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 4,我需要在MySQL表中插入一些行,并且需要找回插入的ID.

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.

对于单行,我可以使用->insertGetId(),但是它不支持多行.如果我至少能像普通的MySQL一样检索第一行的ID,就足以找出其他的ID.

For a single row, I can use ->insertGetId(), however it has no support for multiple rows. If I could at least retrieve the ID of the first row, as plain MySQL does, would be enough to figure out the other ones.

推荐答案

根据用户Xrymz的建议,DB::raw('LAST_INSERT_ID();')返回第一个.

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

根据架构api insertGetId()接受数组

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

所以您必须能够做到

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

也就是说,如果使用MySQL,则可以以此检索第一个ID,然后计算其余的ID.还有一个DB::getPdo()->lastInsertId();函数可以提供帮助.

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.

或者如果使用某些方法重新设置了最后一个ID,您也可以将其计算回第一个插入的ID.

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

编辑

根据评论,我的建议可能是错误的.

According to comments, my suggestions may be wrong.

关于如果另一个用户在其间插入行该怎么办"的问题,它取决于商店引擎.如果使用具有表级锁定的引擎( MyISAM MEMORY MERGE ),则该问题是不明确的,因为不能同时使用两个写入表格.

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.

如果使用行级锁定引擎( InnoDB ),那么另一种可能是只插入数据,然后使用whereIn()方法通过某个已知字段检索所有行,或找出

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.

这篇关于Laravel-多插入行并检索ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆