Eloquent / Laravel:如何获取 updateOrCreate() 的最后插入/更新 ID/实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46936347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent / Laravel: How to get last insert/update ID/instance of updateOrCreate()?
提问by Blackbam
The title is mostly self-explanatory. Eloquent has a method called
标题主要是不言自明的。Eloquent 有一个方法叫做
updateOrCreate()
updateOrCreate()
documented here: https://laravel.com/docs/5.5/eloquent#other-creation-methods
此处记录:https: //laravel.com/docs/5.5/eloquent#other-creation-methods
In some cases this is really useful. However after doing updateOrCreate()
I need either the updated/created object or its primary key or its id.
在某些情况下,这真的很有用。但是,在完成之后,updateOrCreate()
我需要更新/创建的对象或其主键或其 id。
Of course I could do MyModel::where(...)->first()
and give all those data again but this is clumsy and may be some expensive request.
当然,我可以MyModel::where(...)->first()
再次提供所有这些数据,但这很笨拙,而且可能是一些昂贵的请求。
However updateOrCreate()
only returns trueor false.
但是updateOrCreate()
只返回true或false。
Any ideas?
有任何想法吗?
回答by Alexey Mezenin
The method will return ID of created or updated object, so just do this:
该方法将返回创建或更新对象的 ID,因此只需执行以下操作:
$object = Model::updateOrCreate(['name' => 'John'], ['age' => 25]);
$id = $object->id;
回答by Lloople
Query for the last one
查询最后一个
$lastRecord = MyModel::last();
Or
或者
$lastRecord = MyModel::orderBy('id', 'DESC')->first();