简体   繁体   English

Laravel-5在firstOrCreate()之后获取最后一个插入的id

[英]Laravel-5 get last inserted id after firstOrCreate()

I'm trying to get the last inserted ID in the database after a firstOrCreate() call. 我试图在firstOrCreate()调用后获取数据库中最后插入的ID。 I have copied my code below: 我复制了下面的代码:

$booking->firstOrCreate(array_slice($reserve->whereId($payment->reserved_place_id)->first()->toArray(), 0, 24))->save();

How can I get the last ID inserted? 如何插入最后一个ID?

I have looked at the other Laravel requests to get last insert ID but I believe this instance is different because they are not using firstOrCreate(). 我查看了其他Laravel请求获取最后一个插入ID但我相信这个实例是不同的,因为他们没有使用firstOrCreate()。

Thanks in advance. 提前致谢。

firstOrCreate() method returns Model. firstOrCreate()方法返回Model。 So you can simply save it to some variable and then get the model's ID. 因此,您只需将其保存到某个变量,然后获取模型的ID即可。

// Retrieve the flight by the attributes, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);

Returns always a model as stated in the Laravel documents : 返回Laravel文档中所述的模型:

There are two other methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. 您可以使用另外两种方法通过批量分配属性来创建模型:firstOrCreate和firstOrNew。 The firstOrCreate method will attempt to locate a database record using the given column / value pairs. firstOrCreate方法将尝试使用给定的列/值对定位数据库记录。 If the model can not be found in the database, a record will be inserted with the given attributes. 如果在数据库中找不到该模型,则将插入具有给定属性的记录。

$flight->id; //returns the last inserted id or the id of the already created document

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM