使用laravel获取最后插入的id

时间:2016-10-20 07:06:59

标签: php mysql laravel-5

我遇到了问题。 我需要从表中最后插入的id添加到同一个表中,即在我的表中我有两个字段" id" "翻译"他们都应该保存相同的价值。 Id字段是自动增量。如何实现这个????在这种情况下,我也使用excel上传类别同样的问题......请帮助我....

我的控制器功能是

$insert[] = ['translation_lang'=>'en','parent_id' =>$a[0],'name' => $value->name,'slug' =>$value->name,'description' => $value->description,'picture'=>$pic,'active'=>1];

$last_id =    \DB::table('categories')->max('id');  

if(!empty($insert)){                            
    \DB::table('categories')->insert($insert);
    \DB::table('categories')->where('id2',$last_id)->update(['translation_of' => $last_id]);
    return Redirect::to('admin/category');
}

等待回复。

2 个答案:

答案 0 :(得分:2)

而不是使用

\DB::table('categories')->insert($insert);

使用

\DB::table('categories')->insertGetId($insert);

方法insertGetId将插入数据,然后返回插入行的增量ID。

答案 1 :(得分:1)

使用insertGetId代替insert

$id=DB::table('categories')->insertGetId($insert);

$id是您的最后一次插入ID

相关问题