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

后端 未结 6 758
情歌与酒
情歌与酒 2020-12-29 20:12

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 ->

相关标签:
6条回答
  • 2020-12-29 20:22

    There is a insertGetId() method, as follows:

    $dataset = array('column_id' => 1, 'name' => 'Dayle');
    $column_id = DB::table('users')->insertGetId($dataset,'column_id');
    
    0 讨论(0)
  • 2020-12-29 20:22

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

    more info here

    0 讨论(0)
  • 2020-12-29 20:24

    There is a insertGetId method.

    $id = DB::table('users')->insertGetId(
        array('id' => 1, 'name' => 'Dayle Rees')
    );
    
    0 讨论(0)
  • 2020-12-29 20:25

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

    Best thing that you need review docs :

    http://laravel.com/docs/eloquent

    0 讨论(0)
  • 2020-12-29 20:30

    A bit late with the answer but, I think for psql it's best to use native 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()]
    );
    
    0 讨论(0)
  • 2020-12-29 20:46

    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()

    0 讨论(0)
提交回复
热议问题