在 Laravel 4 中使用 DB::insert() 返回新 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15842138/
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
Return new id with DB::insert() in Laravel 4
提问by Nyxynyx
In Laravel 4, when you perform a DB::insert()
, how can you get the ID of the row that has just been inserted? Similar what we have with the function ->insertGetId()
. Reason for using DB::insert()
is that its a complex PostgreSQL query that cannot be built using Fluent.
在 Laravel 4 中,执行 a 时DB::insert()
,如何获取刚刚插入的行的 ID?类似于我们的函数->insertGetId()
。使用的原因DB::insert()
是它是一个复杂的 PostgreSQL 查询,无法使用 Fluent 构建。
Example Query:
示例查询:
$newId = DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
echo $newId; // returns 1
回答by Blessing
There is a insertGetId method.
有一个 insertGetId 方法。
$id = DB::table('users')->insertGetId(
array('id' => 1, 'name' => 'Dayle Rees')
);
回答by Phill Sparks
If you take a look at Illuminate\Database\ConnectionInterface
you can see how these functions are written. Unfortunately DB::insert()
returns a boolean from PDOStatement::execute()
and there is no DB::insertGetId()
at the moment. If this would be useful then you should request it on GitHub.
如果你看一看,Illuminate\Database\ConnectionInterface
你会看到这些函数是如何编写的。不幸的是DB::insert()
返回一个布尔值PDOStatement::execute()
,目前没有DB::insertGetId()
。如果这有用,那么您应该在 GitHub 上请求它。
In the mean time, you should be able to use DB::getPdo()->lastInsertId()
同时,您应该能够使用 DB::getPdo()->lastInsertId()
回答by user5152062
There is a insertGetId()
method, as follows:
有一个insertGetId()
方法,如下:
$dataset = array('column_id' => 1, 'name' => 'Dayle');
$column_id = DB::table('users')->insertGetId($dataset,'column_id');
回答by tylik
A bit late with the answer but, I think for psql it's best to use native RETURNING id
答案有点晚了,但是我认为对于 psql 最好使用本机 RETURNING id
The query that worked for me was:
对我有用的查询是:
DB::select(
DB::raw('insert into threads (created_at, updated_at) values (?, ?)
returning id'), [Carbon::now(), Carbon::now()]
);
回答by Onder OZCAN
If you get in complex structure, better to use Eloquent.
如果您遇到复杂的结构,最好使用 Eloquent。
Best thing that you need review docs :
您需要查看文档的最佳内容: