我想在数据库中插入值时获得当前ID。我将使用它来保存自定义数据。我该怎么做?
我已经写了一个查询。
$currentId = Student::orderBy('id', 'desc')->get(['id']) + 1;
但它显示了以下错误:
Illuminate''Database''Eloquent''Collection类的对象不能转换为int
$currentId = Student::orderBy('id', 'desc')->first()->id + 1;
但在流量大的网站上,这可能会导致数据完整性问题,所以我使用这种方法:
$student = new Student();
....
$student->save();
$currentId = $student->id;
试试这个$data=Student::orderBy('id','desc')->get(['id']);$data->getId();
你必须这样做:-
$insertData['name'] = 'your name';
$insertData['password'] = 'password';
..
等等。。
// $insertData this will be your array which you want to insert in your db. name and password used in insertData array will be same as your table column name..
$lastId = Student::insertGetId($insertData);
它会给你最后插入的身份证在拉拉威尔,它会帮助你。