如何获得最后插入的ID在雄辩的ORM laravel [英] How to get last insert id in Eloquent ORM laravel

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

问题描述

我正在使用Laravel中的雄辩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.

我搜索到最后插入的id在laravel雄辩ORM中,我得到以下链接( Laravel,获得最后插入ID使用Eloquent ),这是指从以下函数获取最后一个插入ID $ data-> save()

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);

我的查询: / strong>

My Query:

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);

这篇关于如何获得最后插入的ID在雄辩的ORM laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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