5

有没有办法last_insert_id在使用 laravel 的原始查询时获得?

DB::query('INSERT into table VALUES ('stuff') ')

这将返回 true 或 false。有没有办法在 Laravel 中使用原始查询获取 last_insert_id ?

4

5 回答 5

18

只是那些可能对 laravel 4 有同样问题的人的好处,@haso-keric 的回复有轻微的语法变化。

这是:

$id = DB::table('users')-> insertGetId (array('email' => 'example@gmail.com')

于 2013-05-06T00:29:03.343 回答
7

试试DB::Query('SELECT LAST_INSERT_ID()')

(这是特定于数据库产品的,我给出的示例是针对 MySQL/MariaDB 的。)

于 2012-11-08T23:10:24.393 回答
3

对于 Laravel 4:

$id = DB::select('SELECT LAST_INSERT_ID()');

解释:

when using the lovely Laravel 4 PHP framework for websites etc, you should refer to the "DB::Select" function instead of "DB::Query" for raw queries. As "DB::Query" throws an error. I believe this is because its deprecated from v3, or plain doesn't exist. Yours, Smith.

于 2014-08-04T15:39:28.993 回答
2

插入具有自动递增 ID 的记录?您可以使用 insert_get_id 方法插入记录并检索 ID:

$id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com')); 注意: insert_get_id 方法要求自动递增列的名称为“id”。

于 2013-02-15T01:14:42.317 回答
0

只需使用底层 PDO 实例:

DB::connection()->getPdo()->lastInsertId();
于 2019-08-03T17:09:38.237 回答