laravel 原始查询 last_insert_id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13299493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:24:37  来源:igfitidea点击:

laravel raw queries last_insert_id

phplaravellast-insert-id

提问by Sinan

Is there a way to get the last_insert_idwhen using laravel's raw query?

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

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

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

This returns true or false. Is there a way to get last_insert_id using raw queries in Laravel?

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

回答by Dele

Just the benefit of those who might have be having the same question for laravel 4, there is a slight syntax change from @haso-keric's response.

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

It is:

这是:

$id = DB::table('users')->insertGetId(array('email' => '[email protected]')

回答by eis

Try DB::Query('SELECT LAST_INSERT_ID()')?

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

(this is DB product specific, example I've given is for MySQL/MariaDB.)

(这是特定于 DB 产品的,我给出的示例适用于 MySQL/MariaDB。)

回答by Smith

For Laravel 4:

对于 Laravel 4:

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

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

Explanation:

解释:

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.

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.

回答by Haso Keric

Inserting a record that has an auto-incrementing ID? You can use the insert_get_id method to insert a record and retrieve the ID:

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

$id = DB::table('users')->insert_get_id(array('email' => '[email protected]')); Note: The insert_get_id method expects the name of the auto-incrementing column to be "id".

$id = DB::table('users')->insert_get_id(array('email' => '[email protected]')); 注意:insert_get_id 方法期望自动递增列的名称为“id”。

回答by DizelGenerator

Just use underlying PDO instance:

只需使用底层 PDO 实例:

DB::connection()->getPdo()->lastInsertId();