Return new id with DB::insert() in Laravel 4

2019-02-05 16:04发布

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.

Example Query:

$newId = DB::insert('insert into users (id, name) values (?, ?)', array(1, 'Dayle'));
echo $newId; // returns 1

5条回答
Fickle 薄情
2楼-- · 2019-02-05 16:19

There is a insertGetId method.

$id = DB::table('users')->insertGetId(
    array('id' => 1, 'name' => 'Dayle Rees')
);
查看更多
【Aperson】
3楼-- · 2019-02-05 16:19

If you get in complex structure, better to use Eloquent.

Best thing that you need review docs :

http://laravel.com/docs/eloquent

查看更多
Juvenile、少年°
4楼-- · 2019-02-05 16:22

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.

In the mean time, you should be able to use DB::getPdo()->lastInsertId()

查看更多
仙女界的扛把子
5楼-- · 2019-02-05 16:28

After saving the data into the DB you just call $insertedId = $user->id; where $user->save() is called before the step.

more info here

查看更多
神经病院院长
6楼-- · 2019-02-05 16:38

There is a insertGetId() method, as follows:

$dataset = array('column_id' => 1, 'name' => 'Dayle');
$column_id = DB::table('users')->insertGetId($dataset,'column_id');
查看更多
登录 后发表回答