我正在使用Laravel 4,我需要在MySQL表中插入一些行,我需要重新插入它们。
对于单行,我可以使用->insertGetId()
,但它不支持多行。如果我至少可以检索第一行的ID,就像普通的MySQL那样,就足以找出其他的那些。
答案 0 :(得分:3)
它的mysql行为 last-insert-id
重要
如果使用单个INSERT语句插入多行,则LAST_INSERT_ID()仅返回为第一个插入行生成的值。这样做的原因是可以轻松地为其他服务器重现相同的INSERT语句。
你可以尝试使用多个插入并带上它或保存后,尝试使用$ data-> id应该是插入的最后一个id。
答案 1 :(得分:0)
正如用户Xrymz建议的那样,DB::raw('LAST_INSERT_ID();')
会返回第一个。
根据Schema api insertGetId()
接受数组
public int insertGetId(array $values, string $sequence = null)
所以你必须能够做到
DB::table('table')->insertGetId($arrayValues);
多数民众赞成说,如果使用MySQL,你可以通过这个来检索第一个id并计算其余的id。还有DB::getPdo()->lastInsertId();
功能,可以提供帮助。
或者,如果它使用某些方法回溯了最后一个id,你可以将它计算回第一个插入的。
修改强>
根据评论,我的建议可能是错误的。
关于“如果其他用户在中间插入行会怎么样”的问题,它在商店引擎上为depends。如果使用具有表级锁定( MyISAM , MEMORY 和 MERGE )的引擎,那么问题是不可逆转的,因为它不能同时是两个写到桌子上。
如果使用了行级锁定引擎( InnoDB ),则另一种可能是插入数据,然后通过whereIn()
的某个已知字段检索所有行方法,或找出table level locking。
答案 2 :(得分:0)
如果你使用的是支持事务的INNODB,那么你可以轻松解决这个问题。 有多种方法可以解决此问题。
假设有一个名为 Users
的表,它有 2 列 id, name
和对 User
模型的表引用。
解决方案 1
您的数据看起来像
$data = [['name' => 'John'], ['name' => 'Sam'], ['name' => 'Robert']]; // this will insert 3 rows
假设表上的最后一个 id 是 600
。您可以像这样在表中插入多行
DB::begintransaction();
User::insert($data); // remember: $data is array of associative array. Not just a single assoc array.
$startID = DB::select('select last_insert_id() as id'); // returns an array that has only one item in it
$startID = $startID[0]->id; // This will return 601
$lastID = $startID + count($data) - 1; // this will return 603
DB::commit();
现在,您知道行在 601
和 603
的范围之间
确保使用此
DB
外观
use Illuminate\Support\Facades\DB;
解决方案 2
此解决方案要求您具有 varchar 或某种文本字段
$randomstring = Str::random(8);
$data = [['name' => "John$randomstring"], ['name' => "Sam$randomstring"]];
你明白了。您将该随机字符串添加到 varchar
或 text
字段。
现在插入这样的行
DB::beginTransaction();
User::insert($data);
// this will return the last inserted ids
$lastInsertedIds = User::where('name', 'like', '%' . $randomstring)
->select('id')
->get()
->pluck('id')
->toArray();
// now you can update that row to the original value that you actually wanted
User::whereIn('id', $lastInsertedIds)
->update(['name' => DB::raw("replace(name, '$randomstring', '')")]);
DB::commit();
现在您知道插入的行是什么了。