问题描述
我使用的是 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,就足以找出其他行了.
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.
根据Schema api insertGetId() 接受数组
public int insertGetId(array $values, string $sequence = null)
所以你必须能够做到
DB::table('table')->insertGetId($arrayValues);
也就是说,如果使用 MySQL,您可以通过此检索第一个 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)