問題描述
我正在使用Laravel 中的 Eloquent ORM"執行數據庫操作.我只想取數據庫中的最后一個插入 id(不是最大 id).
I am performing a database operation with "Eloquent ORM in Laravel". I just want to take the last insert id (not the maximum id) in the database.
我在 Laravel Eloquent ORM 中搜索以獲取最后一個插入 id,我得到了以下鏈接 (Laravel,使用 Eloquent 獲取最后一個插入 id) 是指從以下函數$data->save()
"中獲取最后一個插入 id.
I searched to get last insert id in laravel Eloquent ORM, I got following link (Laravel, get last insert id using Eloquent) that is refer to get last insert id from following function "$data->save()
".
但我需要得到
"Model::create($data)
";
我的查詢:
GeneralSettingModel::create($GeneralData);
User::create($loginuserdata);
如何獲取最后插入的 id?
How can I retrieve the last inserted id?
推薦答案
如文檔所說:插入,更新,刪除
"您也可以使用 create 方法將新模型保存在單個線.插入的模型實例將從方法.但是,在此之前,您需要指定一個模型上的可填充或受保護的屬性,就像所有 Eloquent 模型一樣防止大規模分配.
"You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment.
保存或創建使用自動遞增 ID 的新模型后,您可以通過訪問對象的 id 屬性來檢索 ID:"
$insertedId = $user->id;
所以在您的示例中:
$user = User::create($loginuserdata);
$insertedId = $user->id;
然后在 table2 上它將會是
then on table2 it is going to be
$input['table2_id'] = $insertedId;
table2::create($input);
這篇關于如何在 Eloquent ORM laravel 中獲取最后一個插入 ID的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!