如何在 Eloquent ORM laravel 中获取最后一个插入 ID

How to get last insert id in Eloquent ORM laravel(如何在 Eloquent ORM laravel 中获取最后一个插入 ID)
本文介绍了如何在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)