如何在 Eloquent ORM laravel 中获取最后一个插入 ID [英] How to get last insert id in Eloquent ORM laravel

查看:64
本文介绍了如何在 Eloquent ORM laravel 中获取最后一个插入 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆